我试图从一个危险网站收集数据。特别是,我想从这个site的数据表中收集美元金额:
在lxml中显示如下:
我可以使用以下代码行执行此操作:
scores = [int(score.text.replace('$','').replace(',','')) for score in soupEpisode.find('h3', string='Scores at the first commercial break (after clue 15)').findNext('table').find_all('tr')[1].find_all('td')]
但是,有时表格的显示略有不同(用“16”代替“15”),例如:
因此,我的代码中
soupEpisode.find('h3', string='Scores at the first commercial break (after clue 15)')
将返回“无”。有没有办法只使用h3名称的子字符串来执行find方法?如果我只需要“第一次商业突破时的得分”子字符串就可以编写相同的代码行,我相信它适用于所有情况。谢谢
编辑:
要进行测试,请下载this site的html版本,以下代码段应该可以工作:
from bs4 import BeautifulSoup
def main():
#episode_file should be "8062.html"
episode = open(episode_file, encoding="utf-8")
soupEpisode = BeautifulSoup(episode, 'lxml')
episode.close()
first_commercial_break = [int(score.text.replace('$','').replace(',','')) for score in soupEpisode.find('h3', string=string='Scores at the first commercial break (after clue 15)').findNext('table').find_all('tr')[1].find_all('td')]
return first_commercial_break
试试这个代码。它找到h3,包括“第一次商业休息时的得分”,然后找到h3下的表格
打印结果如下
相关问题 更多 >
编程相关推荐