抓取汉字python

0 encoding beautifulsoup decoding web-scraping python-2.7

我从https://automatetheboringstuff.com学会了如何废弃网站。我想报废http://www.piaotian.net/html/3/3028/1473227.html,里面的内容是中文的,写成.txt文件。但是,.txt 文件包含随机符号,我认为这是编码/解码问题。

我读过这个线程“如何使用 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()))
Run Code Online (Sandbox Code Playgroud)

宏杰李*_*宏杰李 5

novel = requests.get("http://www.piaotian.net/html/3/3028/1473227.html")
novel.raise_for_status()
novel.encoding = "GBK"
novelSoup = bs4.BeautifulSoup(novel.text, "html.parser")
Run Code Online (Sandbox Code Playgroud)

出去:

<br>
    ?????????????????????????????????????????????????<br/>
<br/>
    ????????????????????????????????????????????????????????<br/>
<br/>
    ???????????????????????????????????????????????????????????????????????????????????????<br/>
Run Code Online (Sandbox Code Playgroud)

请求将自动解码来自服务器的内容。大多数 unicode 字符集都是无缝解码的。

当您发出请求时,Requests 会根据 HTTP 标头对响应的编码进行有根据的猜测。访问r.text时使用Requests猜测的文本编码。您可以使用 r.encoding 属性找出请求正在使用的编码并对其进行更改:

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
Run Code Online (Sandbox Code Playgroud)

如果您更改编码,则每当您调用 r.text 时,请求都会使用 r.encoding 的新值。