python - 我的 Beautiful Soup find_all 代码有什么问题?
问题描述
我觉得我错过了一些非常基本的东西,但我被困住了。我只是想用 Beautiful Soup 返回一张桌子,但由于某种原因,它没有按 ID 抓取带有线分数的桌子。我可以在此页面上通过它们的 ID 来定位其他 div 和表,但由于某种原因,这个没有返回任何内容。知道我错过了什么吗?
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
url = 'https://www.sports-reference.com/cbb/boxscores/2020-01-14-19-clemson.html'
html = urlopen(url)
soup = BeautifulSoup(html.read(), 'html.parser')
ls = soup.find_all('table', {"id": "line-score"})
解决方案
正如 Ipellis 所说,您尝试抓取的表格是由 Javascript 添加的。这意味着该表格是在您发出初始请求后呈现的,因此 HTML 代码不包含它。
要从中获取数据,我建议您切换BeautifulSoup
到requests-html
(一个非常相似的库)。这个处理这些 Javascript 案例并处理 Web 请求。
您需要先安装它:pip install requests-html
.
然后,您只需执行以下操作:
from requests_html import HTMLSession
session = HTMLSession()
request = session.get('https://www.sports-reference.com/cbb/boxscores/2020-01-14-19-clemson.html')
request.html.render() # Here is where you render the table
table = request.html.xpath('//table[@id="line-score"]')
我建议您xpath
在寻找元素时使用。这是获取您正在寻找的元素的更好方法。如果您不了解 xpath,这里是W3Schools 的 Xpath 教程。
requests-html
您可以在此处获取文档。
推荐阅读
- java - 无需上网即可调用 Spring 控制器方法
- ios - 聚光灯搜索后显示详细视图控制器
- react-native - React-Native 如何从在 componentDidMount 外部定义的 addEvenListener 调用函数
- python - 如何在odoo中获取新记录ID?
- wso2 - WSO2 IS: How to Set Commonauth Caller Path
- c# - Visual Studio Thread Statement gives Error?
- javascript - Javascript 网格选择事件
- r - 将数据框重新格式化为单行
- php - 未定义索引:sessionName
- angularjs - 如何用mailto写html内容?