使用带有特定标题的beauthulsoup查找特定表

2024-09-30 05:26:14 发布

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

我正在尝试在给定的HTML中定位下面的特定表:

<table class="sidearm-table collapse-on-medium accordion" accordion-table="" sortable-table="">
                        <caption>Tennessee Tech<span class="hide"> - Pitching Stats</span></caption>

我的方法是找到标题,然后继续查找父表,从中我将遍历行以找到我想要的文本(我可以自己完成这一部分)。我相信我的错误是隐藏在这样一个事实中:标题文本继续延伸到span标记中,但是不确定是否是这样。下面给出了执行此操作的代码,但是它继续返回None,因为它找不到表(使用我的语法可能不正确):

^{pr2}$

Tags: 定位文本标题onhtmltableclassmedium
2条回答

我会尝试找到所有的标题,然后像这样匹配标题文本:

from bs4 import BeautifulSoup
import re
import requests


header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

for caption in soup.find_all('caption'):
    if caption.get_text() == 'Tennessee Tech - Pitching Stats':
        table = caption.find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})

执行:

from bs4 import BeautifulSoup


html = """
<table class="sidearm-table collapse-on-medium accordion" accordion-table="" sortable-table="">
<caption>
Tennessee Tech
<span class="hide"> - Pitching Stats</span>
</caption>
</table>
"""

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

table = soup.find('table', {'class': 'sidearm-table'})

print(table.contents)

输出:

^{pr2}$

但找不到您的URL(超时):

http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117

相关问题 更多 >

    热门问题