鱼C论坛

 找回密码
 立即注册
查看: 1626|回复: 1

[技术交流] 纵横网址爬小说 Xpath方式下载生成txt文件

[复制链接]
发表于 2021-11-22 16:39:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
纵横小说网址http://book.zongheng.com/showchapter/1130229.html 爬取小说 生成txt文件
  1. import requests
  2. import os
  3. from lxml import etree
  4. import random
  5. import time
  6. import pymysql

  7. def get_html(url):
  8.     headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
  9.     res = requests.get(url,headers=headers,timeout=600)
  10.     res.encoding = res.apparent_encoding
  11.     #res.encoding = 'UTF-8'
  12.     #res.encoding='gb2312'
  13.     htmlmu = res.text
  14.     return htmlmu
  15. #获取页面
  16. def get_book(url):
  17.     html = get_html(url)
  18.     selector = etree.HTML(html)
  19.     nov_name = selector.xpath('///html/body/div[3]/div[1]/h1/text()')  # 标题
  20.     all_urls = selector.xpath('///html/body/div[3]/div[2]/div[2]/div/ul//a/@href')  # 连接
  21.     nov_name = ' '.join(nov_name)  # 去除前后[]字符
  22.     print("匹配到共%d章节" % len(all_urls))
  23.     k=0
  24.     for part_url in all_urls:
  25.         k += 1
  26.         part_url = f'{part_url}'
  27.         booktxt=get_html(part_url)
  28.         selector = etree.HTML(booktxt)
  29.         title = selector.xpath('//*[@class="title_txtbox"]//text()')  # 标题
  30.         content = selector.xpath('//*[@class="content"]//text()')  # 作者
  31.         title = ' '.join(title)  # 去除前后[]字符
  32.         content = ' '.join(content)  # 去除前后[]字符
  33.         title = title.strip()
  34.         content = content.strip()
  35.         title=f'\n{title}\n\n'
  36.         content=f'\t{content}\n'
  37.         content = content.replace("     ", "\n\n  ")
  38.         new = []
  39.         new.append(title)
  40.         new.append(content)
  41.         down = "./txt/"
  42.         if os.path.exists(down) != True:
  43.             os.makedirs(down)

  44.         print("正在写入第%d章" % k)
  45.         with open("./txt/" + nov_name + ".txt", 'a+', encoding='utf-8')as p:
  46.             p.writelines(new)
  47.         m = random.randint(1,6)
  48.         time.sleep(m)


  49. if __name__ == '__main__':   #主函数
  50.     url="http://book.zongheng.com/showchapter/1130229.html"
  51.     # url=input("请输入采集目录地址:")
  52.     get_html(url)
  53.     get_book(url)
复制代码

评分

参与人数 1荣誉 +5 鱼币 +3 贡献 +2 收起 理由
梦鸩鸩 + 5 + 3 + 2 感谢楼主无私奉献!

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2021-11-23 11:00:30 | 显示全部楼层
可以用,好好学习,共同交流。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-30 23:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表