Python3爬虫时如何处理网页编码问题?

今天刚入手学习 python 爬虫,用的是 python3.6。然后爬取网页时遇到一个编码的问题

在执行以下代码时: request = urllib.request.Request(url) print(request)

response = urllib.request.urlopen(request, timeout=20) 出现了编码的问题,错误代码为: UnicodeEncodeError: 'ascii' codec can't encode characters in position 38-39: ordinal not in range(128)

个人觉得应该是页面中包含 Ascii 编码导致的,不知道该在哪个位置改编码。 谢谢大家


Python3爬虫时如何处理网页编码问题?

11 回复

试试在代码最前面加
#!/usr/bin/python
# -- coding: utf-8 --


遇到编码问题确实头疼,直接上干货。核心就两点:优先用response.encoding自动检测,不行就手动指定或chardet兜底。

1. 自动检测(推荐首选)

import requests
r = requests.get('http://example.com')
r.encoding = r.apparent_encoding  # 关键步骤
print(r.text)

apparent_encoding比默认encoding更准,会分析内容推测编码。

2. 手动指定(知道编码时)

r.encoding = 'gb2312'  # 或gbk、utf-8等

3. 用chardet自动检测(复杂情况)

import requests
import chardet

r = requests.get('http://example.com')
# 检测二进制内容的编码
detected = chardet.detect(r.content)
r.encoding = detected['encoding']
print(r.text)

4. 终极方案(处理乱码页面)

import requests
import chardet
from bs4 import BeautifulSoup

r = requests.get('http://example.com')
# 先尝试requests自动检测
r.encoding = r.apparent_encoding

try:
    soup = BeautifulSoup(r.text, 'html.parser')
except:
    # 如果还乱码,用chardet重新检测
    detected = chardet.detect(r.content)
    r.encoding = detected['encoding']
    soup = BeautifulSoup(r.text, 'html.parser')

print(soup.prettify())

总结:先试apparent_encoding,不行上chardet,最后手动指定。

请提供具体网页 url。

request.encoding=xxx

这个问题我之前也遇到过,并非是“页面中包含 Ascii 编码导致的”,而是因为编译器默认的编码形式是 Ascii,一般通过添加 reload(sys)然后 setdefaultencoding(‘utf8’)。当然在开头还要照#1 楼做。供参考

一楼四楼认真的吗?这应该是网页的编码问题,不是代码的吧。

一个可能是都不出来(第一句错),另一个是输出不输出来(第二句错,比如 cmd 编码是 cp936,如果网页是 utf8 有些字符打不出来)。

建议提供更多信息。另外建议使用 requests

requests 库多好啊 urllib 几乎没怎么用过

同意 5 楼,有可能是 cmd 编码和网页编码不一样
试试 response = urllib.request.urlopen(request, timeout=20).decode(‘XXX’)
XXX 写你抓取网页的编码方式
实在不行 response =unicode(urllib.request.urlopen(request, timeout=20),errors=‘replace’)
会自动替换编码不出来的为’0xfff’,应该可以解决。
另外推荐 requests 模块

我猜你可能用的是 CMD ?

你倒是把要爬的网页贴出来呀

cmd ?

回到顶部