【问题标题】:BeautifulSoup encoding.bytes has no attribute called find_all?BeautifulSoup encoding.bytes 没有名为 find_all 的属性?
【发布时间】:2016-07-04 10:05:49
【问题描述】:
 `self.urlOpen=urllib.request.urlopen("http://facebook.com")
  self.content=self.urlOpen.read()
  soup=BeautifulSoup(self.content,"html5lib")
  self.links=soup.find_all("a")`

'charmap' 编解码器无法在位置编码字符......

所以当我尝试对汤变量进行编码时 self.urlOpen=urllib.request.urlopen("http://facebook.com") self.content=self.urlOpen.read() soup=BeautifulSoup(self.content,"html5lib") soup=soup.encode("utf-8") self.links=soup.find_all("a")

'bytes' 对象没有名为 find_all 的属性

我试过了 self.urlOpen=urllib.request.urlopen("http://facebook.com") self.content=self.urlOpen.read() soup=BeautifulSoup(self.content.decode("utf-8","ignore"),"html5lib") self.links=soup.find_all("a")

但同样的错误发生

那我应该怎么编码呢?

【问题讨论】:

  • 在寻求调试帮助时包括完整的回溯。
  • 还有,soup.encode('utf-8')只是creates a byte-string出了HTML,当然没有方法find_all()
  • 您可能正在遭受this的困扰:您的终端无法处理输出,而不是beautifulsoup等问题。
  • 谢谢@llja Everila.that was breif.but我应该如何编码以防止此类错误?
  • 我正在使用Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25:23) [MSC v.1600 64 bit (AMD64)] on win32

标签: python encoding utf-8 beautifulsoup


【解决方案1】:

问题是什么?
find_all 不应引发编码错误,并且您不应在 bs4.BeautifulSoup 对象上调用 encode,因为 encode 返回一个字节串 - 而不是汤! - 所以你不能打电话给find_all

您是否在任何地方使用soup.prettify()?在这种情况下,这可能是引发错误的行。请包含您的代码的Minimal, Complete and Verifiable example

【讨论】:

  • 但我的问题是如何对其进行编码以便我可以调用 find_all
  • 应该能够使用 find_all。请发布您的代码的代表性示例和错误消息的完整回溯。
  • import urllib import urllib.request from bs4 import BeautifulSoup urlOpen=urllib.request.urlopen("http://facebook.com") content=self.urlOpen.read() soup=BeautifulSoup(content,"html5lib") links=soup.find_all("a") f=open("links.txt","w+") for link in links: href=link.get("href") text=link.text f.write(text + "--\t" + self.href + "\n") f.flush() f.close()
  • 首先,您将href 设置为link.get("href"),但后来在字符串中插入self.href 而不是href - 这应该会引发错误。其次,可能是f.write 引发了错误。尝试使用f = open("links,txt", "w", encoding='utf-8') 打开文件。第三,你的例子对我来说很好。
  • 感谢工作!!f=open("link.txt","w+",encoding="utf-8").
猜你喜欢
  • 2016-12-19
  • 2013-03-30
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多