【问题标题】:Beautiful Soup not parsing full websites HTML codeBeautiful Soup 无法解析完整的网站 HTML 代码
【发布时间】:2019-09-30 19:11:43
【问题描述】:

这是我正在编写的用于抓取网站数据的部分代码。

page = 'https://www.pro-football-reference.com/boxscores/200409090nwe.htm'
sub_data = requests.get(page).text
sub_soup = bs4.BeautifulSoup(sub_data, "html.parser")

for toss in sub_soup.findAll('table', {'class':'suppress_all sortable stats_table now_sortable'}):
print(toss)

即使那行代码不正确,我也尝试了更通用的代码来尝试定位我正在寻找的数据

for toss in sub_soup.findAll('td', {'class':'center'}):
print(toss)

我正在尝试从“游戏信息”表中提取一行文字(谁赢得了投掷 - “Won Toss”) - 在这种情况下,答案应该是“爱国者”。由于某种原因,sub_soup 中缺少游戏信息表的整个 HTML 部分。我也尝试使用不同的解析器,比如html5lib。 sub_soup 中存在一个引用的部分(您可以通过检查站点中的行来查看),但不是 HTML 格式。此部分缺少在网站上看到的实际 HTML 代码等。有人可以帮忙吗?

【问题讨论】:

  • 该页面似乎使用 ajax 异步加载页面。您可能需要像 selenium 这样的浏览器自动化工具来加载整个页面
  • @G.Anderson 好的,我会研究如何实现它。出于好奇,您是如何发现它使用 Ajax 的?
  • 第一次加载该页面时,实际上会弹出一个灰色框,上面写着“请稍候,正在加载数据”或类似的内容

标签: python html beautifulsoup


【解决方案1】:

我喜欢处理体育数据。我以前在专业参考网站上遇到过这个问题。表格是在之后渲染的,因此在大多数情况下,您需要使用 Selenium 让它渲染或如上所述,然后可以提取 html 源代码。但这不是必需的,因为大多数表都在初始 html 响应的 cmets 内。您可以使用 BeautifulSoup 提取 cmets,然后在其中搜索 <table> 标签。

我也更喜欢在我看到或需要拉<table> 标签的任何时候使用熊猫。 Pandas 在后台使用 beautifulsoup,然后完成了大部分工作。您需要做的就是在需要时操作表格。

这将创建一个表列表,只需拉出你想要的那个,它在索引位置1

代码:

import requests
from bs4 import BeautifulSoup
from bs4 import Comment
import pandas as pd


url = 'https://www.pro-football-reference.com/boxscores/200409090nwe.htm'
response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')
comments = soup.find_all(string=lambda text: isinstance(text, Comment))

tables = []
for each in comments:
    if 'table' in each:
        try:
            tables.append(pd.read_html(each)[0])
        except:
            continue

输出:

print (tables[1])
            0                                                  1
0   Game Info                                          Game Info
1    Won Toss                                           Patriots
2        Roof                                           outdoors
3     Surface                                              grass
4     Weather  73 degrees, relative humidity 99%, wind 19 mph...
5  Vegas Line                          New England Patriots -3.0
6  Over/Under                                        44.5 (over)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多