【问题标题】:Can't figure out why soup.find_all() returns an empty list无法弄清楚为什么 soup.find_all() 返回一个空列表
【发布时间】:2020-08-14 06:50:17
【问题描述】:

我是 Python 新手,正在使用 BeautifulSoup 练习网页抓取。

我检查了一些类似的问题,例如this onethis onethis one。但是,我仍然陷入我的问题。

这是我的代码:

import urllib.request
from bs4 import BeautifulSoup

html = urllib.request.urlopen("https://en.wikipedia.org/wiki/List_of_largest_recorded_music_markets").read()
soup = BeautifulSoup(html, 'html.parser')

tbody = soup.find_all('table',{"class":"wikitable plainrowheaders sortable jquery-tablesorter"})

首先,我不认为我正在寻找的网页包含类似问题中提到的 java 脚本。我打算提取这些表中的数据,但是当我执行 print(tbody) 时,我发现它是一个空列表。有人可以看看并给我一些提示吗?

谢谢。

【问题讨论】:

  • jquery-tablesorter 类看起来像是由 javascript 添加的。从class 参数中省略它。
  • 我明白了,抱歉我的粗心。顺便说一句,javascript有一个以“j”开头的类是否大致正确?

标签: python web-scraping beautifulsoup


【解决方案1】:

您必须删除 jquery-tablesorter 部分。它是在页面加载后动态应用的,所以如果你包含它,它就不起作用。

这应该可行:

import urllib.request
from bs4 import BeautifulSoup

html = urllib.request.urlopen("https://en.wikipedia.org/wiki/List_of_largest_recorded_music_markets").read()
soup = BeautifulSoup(html, 'html.parser')

tbody = soup.find('table', {"class": "wikitable plainrowheaders sortable"})
print(tbody)

【讨论】:

  • 我明白了。我删除了javascript部分并且有效。谢谢!
  • 如果这对您有帮助,您能否将答案标记为已解决?谢谢
猜你喜欢
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
相关资源
最近更新 更多