python - 在 Python 中抓取表格时,返回一个空表格

标签 python

我需要使用 Python 中的 BeautifulSoup 库通过网络抓取从网站上获取表格。来自 URL https://www.nytimes.com/interactive/2021/world/covid-vaccinations-tracker.html

当我运行此代码时,我得到一个空表:

import requests
from bs4 import BeautifulSoup
#
vaacineProgressResponse = requests.get("https://www.nytimes.com/interactive/2021/world/covid-vaccinations-tracker.html")
vaacineProgressContent = BeautifulSoup(vaacineProgressResponse.content, 'html.parser')
vaacineProgressContentTable = vaacineProgressContent.find_all('table', class_="g-summary-table  svelte-2wimac")
if vaacineProgressContentTable is not None and len(vaacineProgressContentTable) > 0:
    vaacineProgressContentTable = vaacineProgressContentTable[0]
#
print ('the table =', vaacineProgressContentTable)

输出:

the table = []

Process finished with exit code 0

下面的屏幕截图显示了网页中的表格(左侧)和相关的检查元素部分(右侧):

enter image description here

最佳答案

非常简单 - 这是因为您要搜索的类中有一个额外的空间。

如果将类更改为 g-summary-table svelte-2wimac,则应该正确返回标签。

以下代码应该可以工作:

import requests
from bs4 import BeautifulSoup
#
url = requests.get("https://www.nytimes.com/interactive/2021/world/covid-vaccinations-tracker.html")
soup = BeautifulSoup(url.content, 'html.parser')
table = soup.find_all('table', class_="g-summary-table svelte-2wimac")
print(table)

我也在《纽约时报》互动网站上进行了类似的抓取,空格可能非常棘手。如果您添加了额外的空格或遗漏了一个空格,则会返回空结果。

如果您找不到标签,我建议您先使用 print(soup.prettify()) 打印整个文档,然后找到您计划抓取的所需标签。确保从 BeautifulSoup 打印的内容中复制准确类名称文本

关于python - 在 Python 中抓取表格时,返回一个空表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67144542/

相关文章:

python - cvtColor 断言失败 scn == 3 || scn ==4,但是图像确实有3个 channel 并且存在

python - 打印一个相当具体的矩阵

Python 嵌套字典更新任何嵌套键匹配的值

python - 如何在 XLWings 中引用 Excel 表格列名称?

python - 将 Pandas 值组合到成员组中

python - Django通过表单识别对象

python - 如何从 scikits.learn 分类器中提取信息然后在 C 代码中使用

python - 理解列表的问题(我认为)

python - Numpy 数组到图形

python - 显示我的多线程进程的进度条