【问题标题】:BeautifulSoup HTTPResponse has no attribute encodeBeautifulSoup HTTPResponse 没有属性 encode
【发布时间】:2017-06-14 23:58:23
【问题描述】:

我正在尝试让 beautifulsoup 使用 URL,如下所示:

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://proxies.org")
soup = BeautifulSoup(html.encode("utf-8"), "html.parser")
print(soup.find_all('a'))

但是,我收到一个错误:

 File "c:\Python3\ProxyList.py", line 3, in <module>
    html = urlopen("http://proxies.org").encode("utf-8")
AttributeError: 'HTTPResponse' object has no attribute 'encode'

知道为什么吗?可能与 urlopen 函数有关吗?为什么需要 utf-8?

显然,Python 3 和 BeautifulSoup4 似乎存在一些差异,关于给出的示例(现在似乎已经过时或错误)......

【问题讨论】:

标签: python python-3.x beautifulsoup urlopen


【解决方案1】:

它不起作用,因为urlopen 返回一个 HTTPResponse 对象,而您将其视为直接 HTML。您需要在响应上链接 .read() 方法才能获取 HTML:

response = urlopen("http://proxies.org")
html = response.read()
soup = BeautifulSoup(html.decode("utf-8"), "html.parser")
print (soup.find_all('a'))

您可能还想使用html.decode("utf-8") 而不是html.encode("utf-8")

【讨论】:

  • 嗨乔希,这仍然不适合我,我使用与你完全相同的代码,它给了我一个“字符映射到 ”错误
【解决方案2】:

检查这个。

soup = BeautifulSoup(html.read().encode('utf-8'),"html.parser")

【讨论】:

    【解决方案3】:
    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    html = urlopen("http://proxies.org")
    soup = BeautifulSoup(html, "html.parser")
    print(soup.find_all('a'))
    
    1. 首先,urlopen 将返回一个类似文件的对象
    2. BeautifulSoup 可以接受类似文件的对象并自动解码,您不必担心。

    Document:

    要解析文档,请将其传递给 BeautifulSoup 构造函数。 你可以传入一个字符串或一个打开的文件句柄

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(open("index.html"))
    
    soup = BeautifulSoup("<html>data</html>")
    

    首先将文档转为Unicode,HTML实体转为Unicode字符

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 2013-04-24
      • 2020-11-09
      • 2018-10-16
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多