python3 requests爬取gbk时候遇到编码的坑

python3默认是utf8的,爬取gbk网页的时候会出现乱码 

解决办法 

test.encoding="gbk"
test.text

text不转换会出现错误,python3字符集不支持转码

第二种方法

test.content.decode("gbk")

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。 解码

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。 编码

转载于:https://www.cnblogs.com/xxxuxin/p/11439891.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Python3爬虫示例,可以爬取新浪、网易、今日头条和UC四个网站的新闻标题和内容: ```python import requests from bs4 import BeautifulSoup # 新浪新闻 sina_url = 'https://news.sina.com.cn/' sina_res = requests.get(sina_url) sina_res.encoding = 'utf-8' sina_soup = BeautifulSoup(sina_res.text, 'html.parser') sina_news = sina_soup.select('.news-item h2 a') for news in sina_news: print(news.text, news['href']) # 网易新闻 163_url = 'https://news.163.com/' 163_res = requests.get(163_url) 163_res.encoding = 'gbk' 163_soup = BeautifulSoup(163_res.text, 'html.parser') 163_news = 163_soup.select('.news_default a') for news in 163_news: print(news.text, news['href']) # 今日头条 toutiao_url = 'https://www.toutiao.com/' toutiao_res = requests.get(toutiao_url) toutiao_res.encoding = 'utf-8' toutiao_soup = BeautifulSoup(toutiao_res.text, 'html.parser') toutiao_news = toutiao_soup.select('.title-box a') for news in toutiao_news: print(news.text, 'https://www.toutiao.com'+news['href']) # UC头条 uc_url = 'https://www.uc.cn/' uc_res = requests.get(uc_url) uc_res.encoding = 'utf-8' uc_soup = BeautifulSoup(uc_res.text, 'html.parser') uc_news = uc_soup.select('.news-list a') for news in uc_news: print(news.text, news['href']) ``` 这个爬虫程序使用了requests库和BeautifulSoup库,它首先从每个网站获取HTML页面,然后使用BeautifulSoup从HTML中提取新闻标题和内容。在处理每个网站的HTML页面时,需要根据页面编码设置正确的编码方式,否则可能会出现乱码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值