pychon中爬取网页信息,输出时乱码问题,求解决
课程设计
1
今天练习一下pychon的爬取,就写了一个爬取三国演义的爬虫,结果在输出中文时出现乱码。
import requests
from bs4 import BeautifulSoup
url='https://www.shicimingju.com/book/sanguoyanyi.html'
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
page_text=requests.get(url=url,headers=headers).text
soup=BeautifulSoup(page_text,'lxml')
li_list=soup.select('.book-mulu>ul>li')
fp=open('./三国演义.txt','w',encoding='utf-8')
for li in li_list:
title=li.a.string
detail_url='https://www.shicimingju.com/'+li.a['href']
detail_url_text=requests.get(url=detail_url,headers=headers).text
detail_soup=BeautifulSoup(detail_url_text,'lxml')
div_tag=detail_soup.find('div',class_='chapter_content')
content = div_tag.text
fp.write(title+':'+content+'\n')
print(title,'爬取完毕!!!')
print('全部爬取完毕')
爬出来的全是中文乱码。
已经加入了encoding='utf-8'后依然如此,上网找百度也寻觅无果,求指点
-
import requests from bs4 import BeautifulSoup url='https://www.shicimingju.com/book/sanguoyanyi.html' headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36' } res=requests.get(url=url,headers=headers) res.encoding=res.apparent_encoding page_text=res.text soup=BeautifulSoup(page_text,'lxml') li_list=soup.select('.book-mulu>ul>li') fp=open('./三国演义.txt','w',encoding='utf-8') for li in li_list: title=li.a.string detail_url='https://www.shicimingju.com/'+li.a['href'] detail_url_text=requests.get(url=detail_url,headers=headers).text detail_soup=BeautifulSoup(detail_url_text,'lxml') div_tag=detail_soup.find('div',class_='chapter_content') content = div_tag.text fp.write(title+':'+content+'\n') print(title,'爬取完毕!!!') print('全部爬取完毕')
-
你requests 读取页面文件的编码不对 ,用 res.encoding='utf-8'或res.encoding='gbk'设置下读取页面文件用的编码, 再获取res.text即可,比如
res=requests.get('http://www.xxxx.com')res.encoding='utf-8'#或res.encoding='gbk'print(res.text)
或者也可以设置 res.encoding=res.apparent_encoding 自动从网页的内容中分析网页编码
发表回复