使用BeautifulSoup查找h3,但仅给出其标题的子字符串

2024-09-29 22:00:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个危险网站收集数据。特别是,我想从这个site的数据表中收集美元金额:

enter image description here

在lxml中显示如下:

enter image description here

我可以使用以下代码行执行此操作:

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”),例如:

enter image description here

因此,我的代码中

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


Tags: the代码stringallfindh3replaceat
1条回答
网友
1楼 · 发布于 2024-09-29 22:00:09

试试这个代码。它找到h3,包括“第一次商业休息时的得分”,然后找到h3下的表格

from bs4 import BeautifulSoup
from urllib.request import urlopen
html_content = urlopen('http://www.j-archive.com/showgame.php?game_id=6432')
soup = BeautifulSoup(html_content, "lxml")
for h3 in soup.find_all('h3'):
    if 'Scores at the first commercial break' in h3.text:
        new_html_content = str(soup).split(str(h3))[1]

soup = BeautifulSoup(new_html_content, "lxml")
name_list = [td.text for td in soup.find('table').find('tr').find_all('td')]
dollar_list = [td.text for td in soup.find('table').find_all('tr')[1].find_all('td')]

print(name_list)
print(dollar_list)

打印结果如下

['Kevin', 'Julie', 'Bill']
['$2,800', '$0', '$7,200']

相关问题 更多 >

    热门问题