# 需要的库
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.

最新文章

  1. WebView随学笔记
  2. 把cmd信息中的正常和异常输出分别输出到不同txt文件中
  3. java 读取文件内容 三种形式及效率对比
  4. php函数的传值如果需要引用传递注意的细节
  5. PHP的扩展类 mysqli_stmt:预处理类
  6. Android消息推送怎么实现?
  7. Shell 编程基础之 Until 练习
  8. UESTC 2016 Summer Training #1 Div.2
  9. cocos2d-x Mask的实现及优化
  10. Github实例教程-创建库、创建主页
  11. ASP.Net 重写IHttpModule 来拦截 HttpApplication 实现HTML资源压缩和空白过滤
  12. Springboot与Mybatis整合
  13. 通过修改然后commit的方式创建自己的镜像
  14. [Leetcode 216]求给定和的数集合 Combination Sum III
  15. js获取table中的列的数字的和
  16. 函数式编程之 Python
  17. 美轮美奂!9款设计独特的jQuery/CSS3全新应用插件(下拉菜单、动画、图表、导航等)
  18. grep、find命令整理
  19. 【python】如何安装requests
  20. IOS实现打电话后回调

热门文章

  1. istio1.0 实现蓝绿发布(未完成)
  2. 玩转Linux
  3. Zabbix使用第三方API短信报警
  4. 【NPDP笔记】第七章 产品生命周期管理
  5. 【CUDA开发-并行计算】NVIDIA深度学习应用之五大杀器
  6. 【miscellaneous】【C/C++语言】UTF8与GBK字符编码之间的相互转换
  7. lcd12864菜单
  8. ubuntu Docker安装部署Rancher
  9. GitLab+Jenkins持续集成
  10. Harbor配置自签名证书,docker login+web https访问,helm chart推送应用