爬取三国全篇内容
定位目标:https://www.shicimingju.com/book/sanguoyanyi.html
在这里插入代码片import requests
from bs4 import BeautifulSoup
f=open('./sanguo.txt','w',encoding='utf-8')#文件保存在当前文件夹中
headers={
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36"
}
url="https://www.shicimingju.com/book/sanguoyanyi.html"
page_text=requests.get(url=url,headers=headers).text
#数据解析,标题,详情页的url,章节内容
soup=BeautifulSoup(page_text,'lxml') #实例化soup对象
#可以通过层级选择器定位
a_list=soup.select('.book-mulu>ul>li>a')
for a in a_list:
title=a.string
detail_url='https://www.shicimingju.com'+a['href']
#对详情页发出url请求,解析出章节内容
page_text_detail=requests.get(url=detail_url,headers=headers).text
#注意不能使用上面已经实例化好的soup解析,需要重新实例化新的页面的soup
soup=BeautifulSoup(page_text_detail,'lxml')
# detail_list=soup.select('.chapter_content>p')
# print(detail_list)
div_tag=soup.find('div',class_='chapter_content')
content=div_tag.text
f.write(title+":"+content+"\n")
print(title+" 下载成功!!")
f.close()
运行结果如下:
第一回·宴桃园豪杰三结义 斩黄巾英雄首立功 下载成功!!
第二回·张翼德怒鞭督邮 何国舅谋诛宦竖 下载成功!!
第三回·议温明董卓叱丁原 馈金珠李肃说吕布 下载成功!!
第四回·废汉帝陈留践位 谋董贼孟德献刀 下载成功!!
第五回·发矫诏诸镇应曹公 破关兵三英战吕布 下载成功!!
第六回·焚金阙董卓行凶 匿玉玺孙坚背约 下载成功!!
…
此时,sanguo.txt中就有如下内容
第一回·宴桃园豪杰三结义 斩黄巾英雄首立功:
滚滚长江东逝水,浪花淘尽英雄。是非成败转头空。青山依旧在,几度夕阳红。 白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢。古今多少事,都付笑谈中。
——调寄《临江仙》
........
运行过程还可能会出现以下错误:
ConnectionError: HTTPSConnectionPool(host=‘www.shicimingju.com’,
port=443): Max retries exceeded with url: /book/sanguoyanyi/44.html
(Caused by NewConnectionError(’<urllib3.connection.HTTPSConnection
object at 0x000001D2E2393BC8>: Failed to establish a new connection:
[WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。’))
总之,使用Python使用不到30行的代码就可以爬取一些小说资源了!