python爬虫UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
时间: 2023-11-27 21:47:45 浏览: 38
当爬虫爬取的网页内容包含非UTF-8编码格式的字符时,就会出现UnicodeDecodeError: 'utf-8' codec can't decode byte...的错误。解决方法如下:
1.在请求网页时指定编码格式,例如:
```python
import requests
response = requests.get(url, headers=headers)
response.encoding = 'gbk' # 指定编码格式为gbk
html = response.text
```
2.使用chardet库自动检测编码格式,例如:
```python
import requests
import chardet
response = requests.get(url, headers=headers)
encoding = chardet.detect(response.content)['encoding']
html = response.content.decode(encoding)
```
3.如果以上两种方法都无法解决问题,可以尝试使用try-except语句捕获异常并忽略错误字符,例如:
```python
import requests
response = requests.get(url, headers=headers)
try:
html = response.text
except UnicodeDecodeError:
html = response.content.decode('gbk', 'ignore')
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)