使用BeautifulSoup进行Web抓取返回NoneType

时间:2019-01-18 17:08:57

标签: 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")

但是,即使div在网站上具有正确的ID,它也会返回NoneType。我在做错什么吗?

我在页面上看到具有id main的div:

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:3)

BeautifulSoup's documentation

对此进行了简要介绍。
  

Beautiful Soup为许多不同的解析器提供了相同的接口,但是每个解析器都是不同的。不同的解析器将从同一文档创建不同的解析树。最大的区别在于HTML解析器和XML解析器

     

[...]

     

以下是使用Python的内置HTML解析器解析的同一文档:

     

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

     

类似于html5lib,此解析器将忽略结束的</p>标签。与html5lib不同,此解析器不尝试通过添加标签来创建格式正确的HTML文档。与lxml不同,它甚至不必费心添加标签。

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