def getHtml(url,timeout=20):
try:
headers = {
'Accept-Language': 'zh-cn',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/4.0 (compatible MSIE 6.00 Windows NT 5.1 SV1)',
}
r = requests.get(url,headers=headers,timeout=timeout)
html = r.text
return html
except Exception,ex:
return None
soup = BeautifulSoup(getHtml())
print soup.title
以上代码,如何改进,才能在获取任何网页标题的时候,不至于乱码。
注:提取部分网页的标题的时候会直接乱码显示。如何改进,才能通用?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
有个 chardet 用来检测编码的,如果安装了,BeautifulSoup 貌似会自动调用这个库来检测编码并 decode 成 unicode。
对了,上面是从网上看的。
总之拿到文件编码就好办了。
通用比較困難,有些不給編碼又使用奇怪編碼的網頁很難確定用的什麼。
不過只要知道網頁的編碼,在讀取的時候選區合適的解碼器就好了。
先看看是不是编码问题,如果不是的话,建议再看看是不是gzip加密了,如果是的话需要解密,Python有自带的gzip库,
import gzip
g = gzip.open(path, 'rb')
然后对象g就能当普通文件对象进行操作了(虽然type不是'file')
with open('r.txt','w',encoding='utf-8') as ff:
ff.write(r.text)