【问题标题】:Why isn't find_all() returning complete results?为什么 find_all() 不返回完整的结果?
【发布时间】:2017-09-26 13:32:43
【问题描述】:

尝试检索体育参考页面上的 4 个统计数据框。可以在“tfoot”下找到 4 个统计框(两支球队,基本和高级统计)。但是,以下代码仅返回页面的基本统计信息框:

import requests
from bs4 import BeautifulSoup

r = requests.get("https://www.sports-reference.com/cbb/boxscores/2016-11-11-
villanova.html")

c = r.content
soup = BeautifulSoup(c)

boxes = soup.find_all("tfoot")
len(boxes)

我需要在我的代码中指定什么来检索所有四个框?

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    其中两个表隐藏在一个 HTML 注释中,这些都可以提取如下:

    import requests
    from bs4 import BeautifulSoup, Comment
    
    r = requests.get("https://www.sports-reference.com/cbb/boxscores/2016-11-11-villanova.html")
    soup = BeautifulSoup(r.content, 'html.parser')
    boxes = list(soup.find_all("tfoot"))
    
    for comment in soup.find_all(string=lambda text:isinstance(text, Comment)):
        if 'tfoot' in comment:
            hidden_soup = BeautifulSoup(comment, 'html.parser')
            boxes.extend(list(hidden_soup.find_all("tfoot")))
    
    data = []        
    
    for box in boxes:
        for tr in box.find_all('tr'):
            data.append([td.text for td in tr.find_all('td')])
    
    for row in data:
        print row
    

    给你以下数据:

    [u'200', u'19', u'65', u'.292', u'13', u'33', u'.394', u'6', u'32', u'.188', u'4', u'7', u'.571', u'4', u'22', u'26', u'12', u'3', u'0', u'13', u'15', u'48']
    [u'200', u'33', u'67', u'.493', u'18', u'26', u'.692', u'15', u'41', u'.366', u'7', u'12', u'.583', u'9', u'41', u'50', u'15', u'8', u'4', u'8', u'14', u'88']
    [u'200', u'.351', u'.338', u'.492', u'.108', u'8.9', u'71.0', u'34.2', u'63.2', u'4.0', u'0.0', u'16.0', u'100.0', u'64.0', u'117.3']
    [u'200', u'.605', u'.604', u'.612', u'.179', u'29.0', u'91.1', u'65.8', u'45.5', u'10.7', u'12.1', u'10.0', u'100.0', u'117.3', u'64.0']
    

    【讨论】:

    • 您推荐阅读哪些资源,以便我可以更好地理解 HTML 布局,从而使我的 Web 解析更准确? Beautiful Soup 文档似乎是一个开始的地方,但是当我不确定首先要寻找什么时,它会非常令人不知所措。
    • 我同意在尝试学习 BeautifulSoup 之前最好先了解 HTML。任何 HTML 介绍都会有所帮助。 YouTube 有许多 HTML 介绍性视频供您观看。
    猜你喜欢
    • 2017-06-07
    • 2023-04-04
    • 2023-03-05
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 2013-03-30
    相关资源
    最近更新 更多