AttributeError:“Doctype”对象没有属性“has_attr”

Way*_*yne 6 python attributes hyperlink

该脚本应该提取所有超链接

  import httplib2
import bs4 as bs
from bs4 import SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')

for link in bs.BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
    if link.has_attr('href'):
        print(link['href'])
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

AttributeError: 'Doctype' object has no attribute 'has_attr'
Run Code Online (Sandbox Code Playgroud)

我该如何纠正这个问题,我已经查看了其他地方找不到解决方案。

And*_*huk 3

该问题似乎与解析器相关,因为它仅在lxml解析器中表现出来(在许多系统上是默认的)。使用库存html.parser可以解决这个问题:

for link in bs.BeautifulSoup(response, 'html.parser',
                             parseOnlyThese=SoupStrainer('a')):
    if link.has_attr('href'):
        print(link['href'])
Run Code Online (Sandbox Code Playgroud)