首页 > 解决方案 > 我的 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"})

网络检查器屏幕截图

标签: pythonweb-scrapingbeautifulsoup

解决方案


正如 Ipellis 所说,您尝试抓取的表格是由 Javascript 添加的。这意味着该表格是在您发出初始请求后呈现的,因此 HTML 代码不包含它。

要从中获取数据,我建议您切换BeautifulSouprequests-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 您可以在此处获取文档。


推荐阅读