【问题标题】:Can't get the value of a tag with BeautifulSoup无法使用 BeautifulSoup 获取标签的值
【发布时间】:2023-11-06 06:30:01
【问题描述】:

我刚开始使用 BS4,但我似乎无法找到为什么我无法提取下表中的文本 -> http://pastebin.com/MCQC7wLY

这是我的代码:

    for team in soup.find_all('tr'):
    print team.a.string

我收到以下错误

AttributeError: 'NoneType' 对象没有属性 'string'

我也尝试过其他的东西,比如

for team in soup.find_all('tr'):
    print team.find('a').string

但我总是遇到同样的错误。

这就是 team.find('a') 返回的内容

<a href="/entry/688922/event-history/7/">FC Lasne</a>

我想提取“FC Lasne”

这让我很生气,因为通常我只是做 find('a').string 并且它只是工作

我应该如何进行?

谢谢

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    您示例中的第一个 tr 中没有任何 a 标记。

    你可以忽略任何没有链接的trs:

    for team in soup.find_all('tr'):
        link = team.find('a')
        if link == null:
           continue
        print link.string
    

    虽然你可以这样做:

    soup.find_all('a')
    

    【讨论】:

    • 天哪,我怎么能错过第一个 tr 没有任何 a... 这将教会我长时间编码。感谢您的帮助