python在eclipse环境下的爬虫
用到的包:
import re
import urllib.request
运用正则需要这个jieba库哦
不足之处,希望各位帮忙指出
谢谢啦!
###思路
首先明确目标:
-得到每一章的标题
-得到每一章的内容
网页链接(url):https://xs.sogou.com/list/6232872035/
分析网页源代码可知 该小说的章节url是由两串字符拼凑起来的,
1:先得到主url的html
2:在html通过正则截取到每一章的url,在一个列表里htmlList[]
(先拼凑再写入列表里)
3:接着定义一个函数,用来得到章节的html
4:然后通过正则截取内容
5:正则截取每一章的标题
6:将得到的正文写入文件(每章的标题名设为文件名 .txt)
注意:由于是多级爬取,每一章的url都不一样,那么要等前一个写入完成才能访问下一章的url.
7:可以通过循环将内容写入
for i in range(0,5): #只爬取前5章的内容
x=chapList[i] #每一章的标题
url2=htmlList[i] #每一章的url
print(url2)
html2=getMhtml(url2) #得到每一章的html
htmlList2=getzh(html2) #得到其中一章的正文
write_in_file('{}.txt'.format(x),htmlList2)
为什么只爬取前5章呢?
因为这本小说一共1000多张,全爬取电脑cpu可能会瘫,或者直接终止运行
(可以试试,我没试过)
我之前爬它们的链接的时候eclipse就终止运行了,我也只是在网页运行的代码,检测是否有错。
8:然后找到建的包,右键+刷新(refresh)就能看到了
到此这个小爬虫就结束了
当然后面自己也可以尝试去修改,或是去爬取其他小说,举一反三嘛
###完整 代码
@requires_authorization
#coding:utf-8
'''
爬取网络小说《武道神尊》
author@初学者_言
'''
import urllib.request
import re
#获得第一主html
def getHtml(url1):
#打开链接
page=urllib.request.urlopen(url1)
html1=page.read()
html1=html1.decode('utf-8')
return html1
#得到每个章节的url列表
def getZlian(html):
reg=r'<a class="text-ellips" pbtag="\d+" href="(.+?)" target'
zhre=re.compile(reg)
htmlList=re.findall(zhre,html)
c='https://xs.sogou.com'
return ['https://xs.sogou.com{}'.format(i) for i in htmlList]
#得到每个章节的html
def getMhtml(url2):
page1=urllib.request.urlopen(url2)
html2=page1.read()
html2=html2.decode('utf-8')
#正则截取正文,定规则:左边起始位置,右边(末尾)结束位置
left = html2.find("contentWp")
right = html2.rfind("flwxBottom")
html2 = html2[left:right]
#截取到的正文有些特殊符号的字符串,需要用正常符号替代
dic = {"\r":'',"“":"“","”":"”","…":"..."}
for i in dic:
html2 = html2.replace(i,dic[i])
return html2
#得到正文内容,在一个列表里
def getzh(html2):
reg2=r'<p>(.+?)</p>'
zhre=re.compile(reg2)
htmlList2=re.findall(zhre,html2)
return htmlList2
#将内容写入文件
def write_in_file(filename,li):
with open(filename,'w') as f:
for m in li:
f.write(m +'\n')
#得到目录表,并将每一章的标题写入文件
def getChapter(html1):
rec=r'<a class="text-ellips" pbtag="\d+" href=".+?" target="_blank"><span>(.+?)</span>'
chare=re.compile(rec)
#html=html.decode('utf-8')
chapList = re.findall(chare,html1)
return chapList
html1=getHtml("https://xs.sogou.com/list/6232872035/")
htmlList=getZlian(html1)
chapList=getChapter(html1)
for i in range(0,5): #只爬取前5章的内容
x=chapList[i] #每一章的标题
url2=htmlList[i] #每一章的url
print(url2)
html2=getMhtml(url2) #得到每一章的html
htmlList2=getzh(html2) #得到其中一章的正文
write_in_file('{}.txt'.format(x),htmlList2)
print('ok') #用来检验程序是否进行完
**注意:**在此,首先对被爬取方说声抱歉(虽然是免费小说),尊重正版小说,此文仅是为了学术交流以及经验分享,别学坏哦。
小白:后面还会写个爬取分页网页的代码,请期待一下