使用Xpath爬虫库下载诗词名句网的史书典籍类所有文章。
2024-08-24 12:59:37
# 需要的库
from lxml import etree
import requests
# 请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
# 保存文本的地址
pathname=r'E:\爬虫\诗词名句网\\'
# 获取书籍名称的函数
def get_book(url):
response = requests.get(url,headers)
etrees = etree.HTML(response.text)
url_infos = etrees.xpath('//div[@class="bookmark-list"]/ul/li') for i in url_infos:
url_info = i.xpath('./h2/a/@href')
book_name = i.xpath('./h2/a/text()')[0]
print('开始下载.'+book_name)
# print('http://www.shicimingju.com'+url_info[0])
get_index('http://www.shicimingju.com'+url_info[0])
# 获取书籍目录的函数
def get_index(url):
response = requests.get(url, headers)
etrees = etree.HTML(response.text)
url_infos = etrees.xpath('//div[@class="book-mulu"]/ul/li')
for i in url_infos:
url_info = i.xpath('./a/@href')
# print('http://www.shicimingju.com' + url_info[0])
get_content('http://www.shicimingju.com' + url_info[0])
# 获取书籍内容并写入.txt文件
def get_content(url):
response = requests.get(url, headers)
etrees = etree.HTML(response.text)
title = etrees.xpath('//div[@class="www-main-container www-shadow-card "]/h1/text()')[0]
content = etrees.xpath('//div[@class="chapter_content"]/p/text()')
content = ''.join(content)
book_name=etrees.xpath('//div[@class="nav-top"]/a[3]/text()')[0]
with open(pathname+book_name+'.txt','a+',encoding='utf-8') as f:
f.write(title+'\n\n'+content+'\n\n\n')
print(title+'..下载完成') # 程序入口
if __name__ == '__main__':
url = 'http://www.shicimingju.com/book/'
get_book(url)
控制台查看下载过程;
打开文件夹查看是否下载成功;
done.
最新文章
- WebView随学笔记
- 把cmd信息中的正常和异常输出分别输出到不同txt文件中
- java 读取文件内容 三种形式及效率对比
- php函数的传值如果需要引用传递注意的细节
- PHP的扩展类 mysqli_stmt:预处理类
- Android消息推送怎么实现?
- Shell 编程基础之 Until 练习
- UESTC 2016 Summer Training #1 Div.2
- cocos2d-x Mask的实现及优化
- Github实例教程-创建库、创建主页
- ASP.Net 重写IHttpModule 来拦截 HttpApplication 实现HTML资源压缩和空白过滤
- Springboot与Mybatis整合
- 通过修改然后commit的方式创建自己的镜像
- [Leetcode 216]求给定和的数集合 Combination Sum III
- js获取table中的列的数字的和
- 函数式编程之 Python
- 美轮美奂!9款设计独特的jQuery/CSS3全新应用插件(下拉菜单、动画、图表、导航等)
- grep、find命令整理
- 【python】如何安装requests
- IOS实现打电话后回调