我学会了如何从https://automatetheboringstuff.com中删除网站。我想取消其中内容为中文的http://www.piaotian.net/html/3/3028/1473227.html,并将其内容写入.txt文件。但是,.txt文件包含随机符号,我认为这是一个编码/解码问题。拼音汉字python
我读过这个主题“how to decode and encode web page with python?”,并认为我的网站的编码方法是“gb2312”和“windows-1252”。我试图用这两种编码方法解码,但失败了。
有人可以向我解释我的代码问题吗?我对编程非常陌生,所以请让我知道我的错误观念!
此外,当我从代码中删除“html.parser”时,.txt文件变成空的,而不是至少有符号。为什么会这样?
import bs4, requests, sys
reload(sys)
sys.setdefaultencoding("utf-8")
novel = requests.get("http://www.piaotian.net/html/3/3028/1473227.html")
novel.raise_for_status()
novelSoup = bs4.BeautifulSoup(novel.text, "html.parser")
content = novelSoup.select("br")
novelFile = open("novel.txt", "w")
for i in range(len(content)):
novelFile.write(str(content[i].getText()))
您只需要在网站上找到正确的编码并应用即可。这里是关于agenty的详细教程 - https://www.agenty.com/doc/hosted-app/248/scraping-chinese-or-japanese-websites –