用python爬取笔趣阁小说---python爬虫

需要的导入的包:

import requests
import re

爬取笔趣阁小说:

https://www.biquge.com.cn/

最近在看《超神机械师》就以这个为例分析爬取代码

先到小说的详情页面:

https://www.biquge.com.cn/book/29105/

检索之后可以发现每章小说的网址:
用python爬取笔趣阁小说---python爬虫_第1张图片
用re.findall 获取这些网址保存起来待用:
用python爬取笔趣阁小说---python爬虫_第2张图片
因为这些网址只是后半部分,我们可以加上后半部分,访问章节网址,获取小说:
用python爬取笔趣阁小说---python爬虫_第3张图片
最后保存到文档中就行了:
用python爬取笔趣阁小说---python爬虫_第4张图片

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('
.*?
'
,html,re.S) mulu = re.findall('
(.*?)
'
,html,re.S) i = 0 for url in zhangjie: requ = requests.get(urls+url,headers = headers) htmls = requ.text #获取小说文本 fiction = re.findall('
    (.*?)
'
,htmls,re.S) fiction = str(fiction) #消去多余字符 fiction = re.sub("[|]|

    |
"
,'',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('=====已保存=====')

你可能感兴趣的:(python,正则表达式)