【发布时间】:2016-11-04 14:52:21
【问题描述】:
我正在尝试从网站获取文本数据,但此代码显示了一些错误。请让我知道错误在哪里。
import requests
from bs4 import BeautifulSoup
def getportions(soup):
for p in soup.find_all("p", {"class": ""}):
yield p.text
def readpage(address):
page = requests.get(address)
soup = BeautifulSoup(page.text, "html.parser")
output_text = ''
for s in getportions(soup):
output_text += s.encode("utf8")
output_text += "\n"
print (output_text)
print ("End of article")
fp = open("content.txt", "w")
fp.write(output_text)
if __name__ == "__main__":
readpage("http://yahoo.com")
错误如下图:
output_text += s.encode("utf8")。 TypeError: 无法将 'bytes' 对象隐式转换为 str
【问题讨论】:
-
.encode返回一个bytes对象。你想做什么? -
@MorganThrapp 我正在尝试将内容写入文件
-
你的意思是
decode吗?为什么你认为你需要对utf-8做任何事情? -
@MorganThrapp 如果我将对象设为字符串,那么它包含不必要的字符
标签: python python-3.x utf-8