seo综合查询网站,吉林省软环境建设网站,网站建设流程渠道,邯郸网络运营中心电话多少python爬取书包网文章总结
今天闲来无事去看小说#xff0c;但是发现没办法直接下载#xff0c;所以呢就用python爬虫来下载一波了#xff0c;哈哈…
爬取的是这篇小说#xff1a;剑破九天(是不是很霸气#xff0c;话不多说#xff0c;开始…)
总体思路步骤分为以下三…python爬取书包网文章总结
今天闲来无事去看小说但是发现没办法直接下载所以呢就用python爬虫来下载一波了哈哈…
爬取的是这篇小说剑破九天(是不是很霸气话不多说开始…)
总体思路步骤分为以下三步 1.获得文章的每个章节链接地址 2.获得章节内容 3.保存到指定位置
首先进入到自己想要下载小说的网址按F12进入开发者工具然后单击这个然后在原网页点击章节列表即可发现以下数据 接下来就是提取这个章节的url了我是用的xpath当然也可以用正则和bs4如下代码 book_list res.xpath(//div[classwp b2 info_chapterlist]/ul/li) 此时book_list中就可以得到所有章节的url了第一步完
第二步就是获得章节具体内容了 和第一步相似用xpath即得到章节名和其中一章节内容 章节名称name res.xpath(//h1/text()) 章节内容message_list res.xpath(//dd[idcontents]/text())
获得了自己需要的章节内容后就要进入第三步的保存了不过在一开始保存时在100章左右时用以下代码出现了UnicodeEncodeError这个问题 for m in message:with open(D:\英雄时刻\{name}.txt.format(name剑破九天),a) as f:f.write(m)然后发现是默认编码方式问题其默认为gbk所以需要改成“utf-8”的格式代码如下 for m in message:with open(D:\英雄时刻\{name}.txt.format(name剑破九天),a,encodingutf-8) as f:f.write(m)然后就可以喝一杯茶慢慢等爬取完成了哈哈以下为代码 #剑破九天.textimport requests
import json
from lxml import htmldef get_booklist(n):#获得章节地址url https://www.bookbao99.net/book/201706/05/id_XNTc5MDg2.htmlheader {User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36}response requests.get(url,headers header)response.encoding utf-8res html.fromstring(response.text)book_list res.xpath(//div[classwp b2 info_chapterlist]/ul/li)print(len(book_list))#章节个数for book in book_list:#遍历所有章节try:t book.xpath(a/href)book_url https://www.bookbao99.net t[0]get_message(book_url)print(第{n}章爬取完毕.format(nn))n 1except UnicodeEncodeError:print(出现一个错误)continuedef get_message(url):#提取每个章节内容header {User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36}response requests.get(url,headers header)response.encoding utf-8res html.fromstring(response.text)name res.xpath(//h1/text())n \nname[0]\n\n#print(name[0])message_list res.xpath(//dd[idcontents]/text())message_list.insert(0,n)#print(message_list)save_book(message_list)def save_book(message):#保存for m in message:with open(D:\英雄时刻\{name}.txt.format(name剑破九天),a,encodingutf-8) as f:f.write(m)if __name__ __main__:n 1get_booklist(n)是不是美滋滋。 最后呢欢迎一起讨论爬虫哟~~~