需要的导入的包:
import requests import re
爬取笔趣阁小说:
https://www.biquge.com.cn/
最近在看《超神机械师》就以这个为例分析爬取代码
先到小说的详情页面:
https://www.biquge.com.cn/book/29105/
检索之后可以发现每章小说的网址: 用re.findall 获取这些网址保存起来待用: 因为这些网址只是后半部分,我们可以加上后半部分,访问章节网址,获取小说: 最后保存到文档中就行了:
import requests import re #请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7', 'Referer': 'https://www.biquge.com.cn/' } #网址 url = 'https://www.biquge.com.cn/book/29105/' urls = 'https://www.biquge.com.cn' #获取text req = requests.get(url,headers = headers) html = req.text #获取每章节的网址 zhangjie = re.findall('<dd><a href="(.*?)" >.*?</a></dd>',html,re.S) mulu = re.findall('<dd><a href=".*?" >(.*?)</a></dd>',html,re.S) i = 0 for url in zhangjie: requ = requests.get(urls+url,headers = headers) htmls = requ.text #获取小说文本 fiction = re.findall('<div id="content"> (.*?)</div>',htmls,re.S) fiction = str(fiction) #消去多余字符 fiction = re.sub("[|]|<br><br> |<br>",'',fiction) print(mulu[i]) print('======保存中======') #保存到文本中 print(fiction[2:-2]) with open('超神机械师1.txt','a+') as f: fictions = str(mulu[i]) + '\n' +fiction[2:-2]+'\n' f.writelines(str(fictions)) i +=1 print('=====已保存=====')