抓取网站页面保存到本地
首先发现了一个网站:http://www.qb5200.org/
页面整洁干净,没什么广告,然后里面有很多小说,但是我在TXT格式下载的时候又发现打不开下载链接,但是网页观看体验不好,没办法,只能借助爬虫了
随便用一本小说举个例子:《发个微信去天庭》的链接是这样的:
http://www.qb5200.org/xiaoshuo/76/76175
然后它的第一章小说地址是:
http://www.qb5200.org/xiaoshuo/76/76175/10380512.html
最后一章小说的地址是这样的:
http://www.qb5200.org/xiaoshuo/76/76175/10381905.html
链接基本一样,只是后面的数字不一样,那么就很容易了,然后进入网页页面,发现内容都在<div id=”content”>这个标签里面,然后把内容提取出来把章数调节调节保存到本地就好了,然后写脚本,运行界面就这样
最后的结果是这样:
最后附上代码:
import requests from bs4 import BeautifulSoup import bs4 import os #http://www.qb5200.org/xiaoshuo/76/76175/10380512.html 第一章 #http://www.qb5200.org/xiaoshuo/76/76175/10381905.html 第末章 zhansghu=1 biaoti='' f=open('发个微信去天庭.txt','a',encoding='utf-8') for num in range(10380512,10381906): url = 'http://www.qb5200.org/xiaoshuo/76/76175/'+str(num)+'.html' r = requests.get(url) if(r.status_code!=200): continue r.encoding=r.apparent_encoding html=r.text soup = BeautifulSoup(html,'lxml') #开始处理文本信息 if(biaoti==soup.title.get_text()[9:-6]): continue tishi='\t\t'+soup.title.get_text()[9:-6]+'('+str(zhansghu)+')'+'\n' biaoti=soup.title.get_text()[9:-6] print('当前已经保存'+str(zhansghu)+'章') zhansghu+=1 f.write(tishi) namelist=soup.find_all('div',{'id':'content'}) for s in namelist: f.write(s.get_text()+'\n') # for link in soup.find('div',id='content'): # if(type(link.string)==bs4.element.NavigableString): # f.write(link.string) f.close()
其他的小说,照着这个改改数字就行