gpt4 book ai didi

python - 使用请求和 BeautifulSoup 在页面上找不到元素

转载 作者:行者123 更新时间:2023-12-01 01:15:02 25 4
gpt4 key购买 nike

我正在尝试抓取我最喜欢的大学橄榄球队的网站。我想抓取网页上的两个表格,我编写的代码可以轻松抓取第一个表格。我可以将其放入 pandas 数据框中,然后放入 Excel 中。由于某种原因,我无法弄清楚我无法从网站上抓取第二张 table (防守 table )。我尝试了多种不同的方法来抓取第二个表。我尝试只查找所有表,它找到第一个表很好,但找不到第二个表。我尝试过使用表中列出的属性,但这也不起作用。任何帮助将不胜感激!下面是我用来尝试抓取第二个表的代码:

from lxml import html
import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd

game_summary = 'https://www.sports-reference.com/cfb/schools/iowa/2018/gamelog/'
game_summary_response = requests.get(game_summary, timeout=30)
game_summary_content = BeautifulSoup(game_summary_response.text, 'html.parser')
deffensive_table = game_summary_content.find('table', id='defense')
defensive_game_summary = deffensive_table.find_all('tr')

当我运行该程序时,我收到以下错误:

Traceback (most recent call last):
File "ncaa_stats_scrape.sh", line 24, in <module>
defensive_game_summary = deffensive_table.find_all('tr')
AttributeError: 'NoneType' object has no attribute 'find_all'

最佳答案

您要查找的表包含在返回的 HTML 中,但作为 HTML 注释。该页面包含一些 JavaScript,这些 JavaScript 在页面加载后执行以取消注释表格,以便显示。获取内容的最简单方法是使用可以在检索页面后执行 JavaScript 的库,例如 requests_html。示例:

from requests_html import HTMLSession


url = 'https://www.sports-reference.com/cfb/schools/iowa/2018/gamelog/'
session = HTMLSession()
r = session.get(url)

r.html.render()

table = r.html.find('table#defense')
print(table.html)

关于python - 使用请求和 BeautifulSoup 在页面上找不到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54432681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com