|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
采集小说到本地生成txt文件,采集网站https://www.xbiquge.la,菜鸟写作,欢迎大家交流学习 QQ:343266695
- import requests
- import os
- from lxml import etree
- import random
- import time
- import pymysql
- def get_html(url):
- 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"}
- res = requests.get(url,headers=headers,timeout=600)
- res.encoding = res.apparent_encoding
- #res.encoding = 'UTF-8'
- #res.encoding='gb2312'
- htmlmu = res.text
- #print(html)
- return htmlmu
- #获取页面
- def get_book(url):
- html = get_html(url)
- selector = etree.HTML(html)
- nov_name = selector.xpath('//*[@id="info"]/h1/text()') #标题
- all_urls = selector.xpath('//*[@id="list"]/dl/dd/a/@href') #连接
- nov_name = ' '.join(nov_name) # 去除前后[]字符
- print(nov_name)
- print("匹配到小说共%d章节" % len(all_urls))
- k=0
- for part_url in all_urls:
- k += 1
- part_url = f'{www}{part_url}'
- booktxt=get_html(part_url)
- # print(booktxt.status_code)
- selector = etree.HTML(booktxt)
- title = selector.xpath('//*[@id="wrapper"]//div//h1/text()') # 标题
- content = selector.xpath('//*[@id="content"]/text()') # 作者
- content = str(content)
- title = ' '.join(title) # 去除前后[]字符
- title = title.replace("正文卷", "")
- content = content.replace("\\xa0\\xa0\\xa0\\xa0", "  ")
- content = content.replace("\\r', '\\r', '", "\n\n")
- content = content.replace("['", "\n\n")
- content = content.replace("………………']", "")
- content = content.replace("']", "\n\n")
- content = content.replace("<br/>\\ufeff", "\n\n")
- content = content.replace("新书就是幼苗,需要大家的呵护才能成长,求推荐票,求收藏,求大家的支持!)", "")
- content = content.replace("<br/>【接近6000字的大章,因为里面有不少设定,所以就不断章了,不想看设定可以跳过去,反正也不重要(认真脸)】<br/>        ……<br/>",
- "<br/>")
- new = []
- new.append(title)
- new.append(content)
- down = "./txt/"
- if os.path.exists(down) != True:
- os.makedirs(down)
- print("正在写入第%d章" % k)
- with open("./txt/" + nov_name + ".txt", 'a+', encoding='utf-8')as p:
- p.writelines(new)
- m = random.randint(3,6)
- time.sleep(m)
- if __name__ == '__main__': #主函数
- url="https://www.xbiquge.la/28/28564/"
- www="https://www.xbiquge.la"
- #url="http://www.shuquge.com/txt/139403/index.html"
- # url=input("请输入采集目录地址:")
- get_html(url)
- get_book(url)
复制代码 |
|