使用Regex从表中提取结果



我正试图从一系列类似的网站上抓取表格。这是一个给我带来麻烦的页面:

失败URL:https://www.nysenate.gov/legislation/bills/2011/s79

成功URL:https://www.nysenate.gov/legislation/bills/2013/s97

使用BeautifulSoup,刮刀拉下桌子,将所有td变成一个列表。然后使用regex,我运行一个if语句,看看它是否有我要查找的信息。

如果是这样,那么它应该被填充到一个数据帧中。只是有些网页没有。我比较了这适用于和不适用于的页面之间的响应文本。

我有一个print语句吐出了整个列表,并在这些列表上测试了我的regex(它们有效(。但我绝对不明白为什么scraper一再无法从同一页中提取相同的信息,并继续在其他页面上。这是相关代码:

check_list = [item.text.strip() for item in tablebody.select("td")]
tablebody=soup.select_one(".table.c-bill--actions-table > tbody")
check_list = [item.text.strip() for item in tablebody.select("td")]
signed_regex = re.compile('(?i)signed')
signed_index = "signed"
try:       
if any(signed_regex.match(thing) for thing in check_list):
transfer_list.append("true")
transfer_list.append(check_list[0])
elif signed_index in check_list:
i = check_list.index(signed_index)
transfer_list.append("true")
transfer_list.append(check_list[0])

else:
transfer_list.append("false")
transfer_list.append("no date")
except Exception as e:
transfer_list.append(e)

看起来您可以使用:contains以该文本为目标,然后使用parent.td移动到之前的td以获取日期

import requests, re
from bs4 import BeautifulSoup as bs
links = ['https://www.nysenate.gov/legislation/bills/2013/s97', 'https://www.nysenate.gov/legislation/bills/2011/s79']
transfer_list = []
with requests.Session() as s:
for link in links:
r = s.get(link)
soup = bs(r.content, 'lxml')
target = soup.select_one('.cbill--actions-table--row td:contains("signed")')
if target:
transfer_list.append("true")
transfer_list.append(target.parent.td.text)
else:
transfer_list.append("false")
transfer_list.append("no date")

最新更新