python - 使用 BeautifulSoup 进行网页抓取返回 NoneType

标签 python beautifulsoup

我正在尝试使用 BeautifulSoup 抓取网站并编写了以下代码:

import requests
from bs4 import BeautifulSoup

page = requests.get("https://gematsu.com/tag/media-create-sales")
soup = BeautifulSoup(page.text, 'html.parser')

try:
    content = soup.find('div', id='main')
    print (content)
except:
    print ("Exception")

但是,这会返回一个 NoneType,即使该 div 在网站上存在且具有正确的 ID。我做错了什么吗?

我在页面上看到了 id 为 main 的 div:

enter image description here

当我打印 soup 时,我也找到了 div main:

enter image description here

最佳答案

这在 BeautifulSoup's documentation 中有简要介绍。

Beautiful Soup presents the same interface to a number of different parsers, but each parser is different. Different parsers will create different parse trees from the same document. The biggest differences are between the HTML parsers and the XML parsers

[ ... ]

Here’s the same document parsed with Python’s built-in HTML parser:

BeautifulSoup("<a></p>", "html.parser")

Like html5lib, this parser ignores the closing </p> tag. Unlike html5lib, this parser makes no attempt to create a well-formed HTML document by adding a tag. Unlike lxml, it doesn’t even bother to add an tag.

您遇到的问题可能是由于格式错误的 HTML 造成的 html.parser无法妥善处理。这导致了 id="main"当 BeautifulSoup 解析 HTML 时被剥离。通过将解析器更改为 html5liblxml , BeautifulSoup 处理格式错误的 HTML 的方式不同于 html.parser

关于python - 使用 BeautifulSoup 进行网页抓取返回 NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54258559/

相关文章:

python - 网页抓取到 .csv

Python:从csv中提取特定行作为列表

python - Python 中的子字符串。内存中的副本?

python - 为什么功能不起作用?试图替换字符串中的单词

python - 如何获取谷歌 "fast answer box"文本?

python - BeautifulSoup 找不到 xml 标签,我该如何解决?

python - 在 Python 中打印字符串,不带句号进入下一行

python - 将我的离线绘图保存为本地 html 文件

python - BeautifulSoup 无法连接 str 和 NoneType 对象

python - 获取指向包含某些文本的标签的xpath