【问题标题】:BeautifulSoup's find_all method going in loopBeautifulSoup 的 find_all 方法进入循环
【发布时间】:2018-08-06 09:54:51
【问题描述】:

我正在使用 BeautifulSoup 进行一些抓取练习,但我生成了一个似乎在循环中的事件。

这是我的代码:

from bs4 import BeautifulSoup
import requests

# Print all links in the page

linkpage = "https://automatetheboringstuff.com/chapter12/"
page = requests.get(linkpage)
page.econding = "utf-8"
data = page.text
html = BeautifulSoup(data, "html5lib")

for link in html.find_all("a"):
    print(link)

当我执行这个脚本时,CPU 达到最大值,没有打印任何内容,并且执行循环。为什么?

两个重要的考虑:

  • 这仅在 Linux 下发生(Python 2 和 3 都适用)。 我在 Windows 下没有得到相同的行为:效果很好,所有链接都打印正确! :-|

  • 只有在变量 linkpage 中指示的 URL 才会发生这种情况。当我与其他人(即https://stackoverflow.com/)更改它时,它可以正常工作。

编辑:

将解析器更改为 xml 即可。

为什么我在使用 html5lib 时会遇到这个问题(目前仅在这个特定页面上)?

【问题讨论】:

  • 对我来说工作正常(linux/python3),也试过lxml解析器,没关系。您确定这是给您带来问题的网址吗?
  • 尝试 findAll() 而不是 find_all() 并检查
  • @AndrejKesely,使用 lxml 解析器就可以了!我测试过的所有其他 URL 都没有这个问题。仅使用此 URL 执行不会出错,但仍处于循环状态。
  • @SmashGuy,我测试了 findAll(),但它的行为与 find_all() 相同。
  • 我们感兴趣的是您更改页面编码的原因吗?这可能会干扰 html5 解析器。

标签: python beautifulsoup


【解决方案1】:
试试这个 从 bs4 导入 BeautifulSoup 导入请求 # 打印页面中的所有链接 链接页=“https://automatetheboringstuff.com/chapter12/” page = requests.get(linkpage) page.econding = "utf-8" 数据 = page.text html = BeautifulSoup(数据) all_link=html.find_all('a') all_link 中的链接: 打印(链接.get('href'))

【讨论】:

  • 之所以有效,是因为它使用 xlml 作为默认解析器。如果我设置 html = BeautifulSoup(data, "html5lib") 我有相同的“循环”执行。
猜你喜欢
  • 2020-07-27
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
  • 2019-12-20
相关资源
最近更新 更多