首页 > 解决方案 > 在python中搜索多个子字符串的列表?

问题描述

所以我有一个包含 10-15 个链接的列表,我想搜索包含“sen_floor”或“asm_floor”的链接

这是我到目前为止的代码(ca_data 是原始链接):

import requests
from bs4 import BeautifulSoup
import re

ca = requests.get(ca_data)
soup = BeautifulSoup(ca.content, 'html.parser')
links = []

for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
   links.append(link.get('href'))

r = re.compile(".*vote")
newlist = list(filter(r.match, links))
print(newlist)

subs = 'sen_floor'
sen_votes = list(filter(lambda x: subs in x, newlist))
print(str(sen_votes))

这有效地返回包含所有链接的列表sen_floor。理想情况下,我希望有一个单独的列表asm_floor。我试着重复最后一段:

sub = 'asm_floor'
asm_votes = list(filter(lambda x: sub in x, newlist))
print(str(asm_votes))

但它不起作用,只是返回与 sen_floor 搜索相同的结果。

帮助?

标签: pythonbeautifulsoup

解决方案


import requests
from bs4 import BeautifulSoup

r = requests.get(
    "http://www.legislature.ca.gov/cgi-bin/port-postquery?bill_number=ab_2&sess=CUR&house=B&author=alejo_%3Calejo%3E")

soup = BeautifulSoup(r.text, 'html.parser')

sen = []
asm = []
for item in soup.findAll("a", {'href': True}):
    item = item.get("href")
    if 'sen_floor' in item:
        sen.append(item)
    elif 'asm_floor' in item:
        asm.append(item)

推荐阅读