我正在尝试使用 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:
当我打印 soup
时,我也找到了 div main:
最佳答案
这在 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 时被剥离。通过将解析器更改为 html5lib
或 lxml
, BeautifulSoup 处理格式错误的 HTML 的方式不同于 html.parser
关于python - 使用 BeautifulSoup 进行网页抓取返回 NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54258559/