import requests
from bs4 import BeautifulSoup
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360S'
}
url='https://www.shicimingju.com/book/sanguoyanyi.html'
page_text=requests.get(url=url,headers=headers).text
#encode编码,将ISO-8859-1编码成unicode
page_text=page_text.encode("ISO-8859-1")
#decode解码,将unicode解码成utf-8
page_text=page_text.decode("utf-8")
#print(page_text)
soup=BeautifulSoup(page_text,'lxml')
li_list=soup.select('.book-mulu > ul > li')
fp=open('./sanguo.txt','w',encoding='utf-8')
for li in li_list:
title=li.a.string
detail_url='https://www.shicimingju.com'+li.a['href']
detail_page_text=requests.get(url=detail_url,headers=headers).text
# encode编码,将ISO-8859-1编码成unicode
detail_page_text = detail_page_text.encode("ISO-8859-1").decode("utf-8")
detail_soup=BeautifulSoup(detail_page_text,'lxml')
div_tag=detail_soup.find('div',class_='chapter_content')
content=div_tag.getText()
fp.write(title+':'+content+'\n')
print(title+' 爬取成功')