用Python做的爬取“笔趣阁”的小说简单爬虫(校花的贴身高手为例)
2019-03-04 19:47
447 查看
用Python做的爬取“笔趣阁”的小说简单爬虫
- 话不多说先上代码,备注都在代码内
#导入所需要用的包 import requests from lxml import etree # 爬取网页中的网址和标题 def title_info(url,headers): #发送请求 response = requests.get(url=url,headers=headers) html = response.text #使用Xpath方式匹配到所需的内容 count = etree.HTML(html) #获取每个标题 title = count.xpath('//a[@style]/text()') #获取url地址 href = count.xpath('//dd/a/@href') get_info(title,href,url) # 获取文章 def get_info(title,href,url): for_num = 0 #文章页数为所有标题的个数 page = len(title) #去掉无用的href链接 href.remove('/0_671/4962666.html') #循环链接 for nums in href: for_num += 1 # 获取href链接的长度 numss = len(nums) #如果长度大于正常长度 #一般有两种长度 # 4972271.html # /0_671/4972271.html #两者不一样,拼接的url地址也不同 #判断是否大于正常长度,如果不是那就重新赋值url if numss > 12: url = 'https://www.xs.la' #进行拼接 url1 = url + nums #发送请求 response = requests.get(url=url1, headers=headers) html = response.text count = etree.HTML(html) #拿到内容 article = count.xpath('//div[@id="content"]/text()') info_article = "" # 定义一个空字符串,接收内容 nums = 0 # 循环出小说的内容 for i in article: article_long = len(article) # 小说的长度 nums += 1 i2 = "\n" + i #用字符串拼接的方式,'\n'是换行的意思 info_article += i2 #再拼接(与上面一步可以拼在一起) #如果循环次数等于小说长度 写入小说 if nums == article_long: print("正在下载第{}章".format(page)) with open("./校花的贴身高手/第{}章.txt".format(page),'w+',encoding="utf-8") as f: f.write(info_article) print("第{}章下载完成".format(page)) page -= 1 if __name__ == '__main__': url = "https://www.xs.la/0_671/" #小说目录网址 headers = { "User - Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 72.0.3626.119Safari / 537.36" } #次数多了可能会被封,所以要使用代理IP title_info(url,headers)
相关文章推荐
- python用字符串操作20行代码简单爬虫入门+案例(爬取一章《三体》小说)
- python3.5爬虫完成笔趣阁小说的爬取
- python爬虫01-创建一个简单的爬虫(附赠爬取的100G某小说网数据库)
- Python爬虫——从笔趣阁爬小说
- python爬虫简单总结
- ”Python开发简单爬虫“慕课网课程学习笔记1
- 利用python实现简单的爬虫,爬百度文库相关词条信息
- python爬虫日志(8)python操作mysql的简单知识
- python_慕课\Python开发简单爬虫\7-7 开始运行爬虫和爬取结果展.py
- python利用urlib2进行简单爬虫实例
- Python之Scrapy爬虫框架安装及简单使用
- python 爬虫简单使用
- 从零开始写Python爬虫 --- 1.7 爬虫实践: 排行榜小说批量下载
- Python简单爬虫——淘宝数据
- 简单的python2.7基于bs4和requests的爬虫
- [Python]网络爬虫(六):一个简单的百度贴吧的小爬虫(转)
- 「实战演练」Python爬虫,使用2.3 Scrapy 框架爬免费小说
- Python3简单爬虫之下载相关类型音乐(喜马拉雅网站)
- 基于python爬虫的简单实现
- python简单爬虫(二)