首页 > 解决方案 > 无论我尝试什么,BeautifulSoup4 都找不到表

问题描述

我正在尝试同时从网页中抓取 2 个表格。BeautifulSoup 找到第一个表没有问题,但无论我尝试什么都找不到第二个表,这是网页:曲棍球参考:Justin Abdelkader

它是季后赛标题下方的表格。

这是我的代码。

        sauce = urllib.request.urlopen('https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014', timeout=None).read()
        soup = bs.BeautifulSoup(sauce, 'html5lib')
        table = soup.find_all('table')
        print(len(table))

总是打印 1。

如果我打印(汤),并在终端中使用搜索功能,我可以找到 2 个单独的表格标签。我没有看到任何会阻碍 BS4 查找标签的 javascript。我也尝试通过 id 和 class 查找表,即使表的父 div 似乎也无法找到。有谁知道我做错了什么?

标签: pythonpandasbeautifulsoup

解决方案


由于 javascript 加载附加信息

今天requests_html可以加载 html 页面也可以加载 javascript 内容。

pip install requests-html

from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014')
r.html.render()
res = r.html.find('table')
print(len(res))
4

推荐阅读