今天练习一下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('全部爬取完毕')
爬出来的全是中文乱码:
你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 自动从网页的内容中分析网页编码
你题目的解答代码如下:
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('全部爬取完毕')
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!