小说内容爬取

人生是一个不断潜行学习的过程,加油!!! / 2024-03-22 / 原文

1、进入主页面 http://www.biquw.la/book/140665/

 2、分析找到每个章节的url

 把鼠标放在这里会显示出隐藏的链接,可以知道每章节的完整的url:

http://www.biquw.la/book/140665/55195587.html

 通过拼接得到每个章节的url

 3、进入章节的页面找到对应标题

 

 4、进入章节的页面找到对应内容

   # 获取小说内容,把每段小说拼接成完整一篇小说 ''.join

  book_data=''.join(detail_data.xpath('//div[@id="htmlContent"]//text()'))
5、写入文件


源代码:
import requests  # 使用requests爬取网络数据,先导入
from lxml import etree # 从lxml库中导入etree,用来解析数据
# 为了方便使用给这个网址定义一个变量
url="http://www.biquw.la/book/140665/"

# 使用类似浏览器的工具在代码中访问网址,requests(看成python浏览器)---可以用来访问网址
response=requests.get(url)
# 服务器端回应状态码200,还有对应数据
response.encoding='utf-8'  # 不写的话会乱码
# print(response) # <Response [200]>

# print(response.text)
html=response.text
# 拿到html数据之后,需要对这一堆数据解析、整理,使用到的整理工具lxml
elements=etree.HTML(html)
print(elements) # <Element html at 0x23a5589c988>
# 获取小说每章节的url,需要的数据都在html中
all_li=elements.xpath('//div[@class="book_list"]/ul/li')
# 把拿到的小说信息进行一个一个处理,模拟人来点击这个链接进入到小说详情页
for book in all_li:
     href=book.xpath('./a/@href')[0] # 得到 55195587.html

     # 每个章节的url
     book_url=url+href
     print(book_url)

#     # 接下来知道网址了 直接试用requests访问即可
     book_resp=requests.get(book_url)
     # 获取小说详情页数据
     book_resp.encoding='utf-8' # 乱码

     book_html=book_resp.text
     # 解析/整理
     detail_data=etree.HTML(book_html) # 解析数据
     # 进入章节页面获取每章节的标题
     book_title=detail_data.xpath('//div[@class="h1title"]/h1/text()')[0]

     print(book_title)
#     # 获取小说内容,把每段小说拼接成完整一篇小说 ''.join
     book_data=''.join(detail_data.xpath('//div[@id="htmlContent"]//text()'))
     # print(book_data)
    # 把小说的标题及内容 写入文件
    #  with open(r'D:\小说'+book_title+'.txt','a',encoding='utf-8')as f:
     with open(r'D:\小说' + book_title + '.txt',  'w',encoding='utf-8',newline='') as f:
         f.write(book_data)
         print(book_title+'.txt 下载成功')

存在的问题:

按以上无法正常写入文件,待处理