【问题标题】:AttributeError: 'bytes' object has no attribute 'find_all' after encoding in PythonAttributeError: 'bytes' 对象在 Python 中编码后没有属性 'find_all'
【发布时间】:2016-04-26 07:42:04
【问题描述】:

我收到以下错误。我在谷歌上搜索得够多了。但没有什么能解决我的问题。我的问题似乎与其他人不同。我正在使用BeautifulSoup

我认为下面一行造成了问题。

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

当我试图找到所有具有holder 类的div 时:

data = soup.find_all("div", {"class":"holder"})

如果显示如下错误:

Traceback(最近一次调用最后一次): 文件“web_crawler.py”,第 32 行,在 数据 = soup.find_all("div", {"class":"holder"}) AttributeError: 'bytes' 对象没有属性 'find_all'

encoding 是否造成了问题?

【问题讨论】:

  • 为什么首先要编码BeautifulSoup 对象?你的意思是写BeautifulSoup(req.content.encode("utf-8"), 'html.parser')之类的东西吗?
  • encoding之前,它显示以下错误:Traceback (most recent call last): File "web_crawler.py", line 33, in <module> print(data); exit() File "c:\Users\DELL\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp 437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xae' in position 13 5: character maps to <undefined>

标签: python django beautifulsoup


【解决方案1】:

req.content 值转换为 utf-8 而不是 BS 对象的值。

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

or

我假设您正在使用 requests 模块来获取 http 响应。

req.encoding = 'utf-8'
soup = BeautifulSoup(req.content, 'html.parser')

【讨论】:

  • 显示:Traceback (most recent call last): File "web_crawler.py", line 29, in <module> soup = BeautifulSoup(req.content.encode("utf-8"), 'html.parser') AttributeError: 'bytes' object has no attribute 'encode'
  • 似乎它已经被编码了.. 在获取它的内容之前,将它的编码设置为 utf-8 就像 req.encoding='utf-8' 然后运行 ​​soup = BeautifulSoup(req.content, 'html.parser'), doc
  • 编码前出现如下错误:Traceback (most recent call last): File "web_crawler.py", line 33, in <module> print(data); exit() File "c:\Users\DELL\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp 437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xae' in position 13 5: character maps to <undefined>
  • 同上:` return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xae' in position 13 5: character映射到 `
【解决方案2】:

您应该对 html 内容进行编码,而不是像这样对 BeautifulSoup 对象进行编码:

BeautifulSoup(req.content.encode("utf-8"), 'html.parser')

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多