爬虫源码—爬取自己想要看的小说

前言:

小说作为在自己空闲时间下的消遣工具,对我们打发空闲时间很有帮助,而我们在网站上面浏览小说时会被广告和其他一些东西影响我们的观看体验,而这时我们就可以利用爬虫将我们想要观看的小说下载下来,这样就不会担心广告的影响了。

一:环境配置

Python版本:3.7.3

IDE:PyCharm

所需库:requests,lxml,time

二:准备工作

1:安装好我们所需要的库。 

2:我们需要在电脑上的指定位置来创建一个文件夹来保存我们爬取的小说。

3:需要去下载XPATH插件以便于我们获取小说的名字(资源已上传,可自行下载安装)。

三:具体代码实现

import requests
from lxml import etree
import time
url = 'https://www.biquge365.net/newbook/33411/'
head = {
    'Referer': 'https://www.biquge365.net/book/33411/',
    'users-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.39'
}
response = requests.get(url,headers = head,verify = False)
# print(response.text)
html = etree.HTML(response.text)
novel_name = html.xpath('/html/body/div[1]/div[3]/div[1]/h1/text()')[0]
novel_directory = html.xpath('/html/body/div[1]/div[4]/ul/li[*]/a/@href')
#由于网站可能具有反扒措施,所以我们设置一下时间,防止被反扒
time.sleep(6)
for i in novel_directory:
    com_url = 'https://www.biquge365.net'+i
    response2 = requests.get(com_url,headers=head)
    html2 = etree.HTML(response2.text)
    novel_chapter = html2.xpath('//*[@id="neirong"]/h1/text()')[0]
    novel_content = 'n'.join(html2.xpath('//*[@id="txt"]/text()'))
    with open('E:\python源码\爬虫教程\小说.txt'+novel_chapter+'.txt','w',encoding='utf-8') as file:
        file.write(novel_chapter+'n'+novel_content+'n')
        file.close()
        print("下载成功"+novel_chapter)

四:结果展示

d93252edb9fc4bfa9704bd0464967458.png

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>