原文跳转:https://blog.csdn.net/Uupton/article/details/80566285
要爬取的网站是:http://www.quanshuwang.com/book/44/44683
import re
import urllib.request
#定义一个爬取网络小说的函数
def getNovelContent():
html = urllib.request.urlopen("http://www.quanshuwang.com/book/44/44683").read() # 解释参考1
html = html.decode("gbk") #转成该网址的格式 # 解释参考2
#<li><a href="http://www.quanshuwang.com/book/44/44683/15379609.html" title="引子 穿越的唐家三少,共2744字">引子 穿越的唐家三少</a></li> #参考
reg = r'<li><a href="(.*?)" title=".*?">(.*?)</a></li>' #正则表达的匹配 # 解释参考3
reg = re.compile(reg) #可添加可不添加,增加效率 # 解释参考4
urls = re.findall(reg,html) # 解释参考5
for url in urls:
#print(url)
chapter_url = url[0] #章节的超链接
chapter_title = url[1] #章节的名字
#print(chapter_title)
chapter_html = urllib.request.urlopen(chapter_url).read() #正文内容源代码 # 解释参考6
chapter_html = chapter_html.decode("gbk")
chapter_reg = r'</script> .*?<br />(.*?)<script type="text/javascript">'
chapter_reg = re.compile(chapter_reg,re.S)
chapter_content = re.findall(chapter_reg,chapter_html)
for content in chapter_content:
content = content.replace(" ","")
content = content.replace("<br />","")
# print(content)
f = open('{}.txt'.format(chapter_title),'w')
f.write(content)
getNovelContent()
运行结果:
解释参考:
一:
我们调用了urllib库的方法,urlopen方法中我们传进一个网址作为参数表示我们需要爬取的网站,.read()方法表示获取源代码。那我们现在打印html是否能成功在控制台把页面的代码给输出了呢?答案是否定的,现在获取的源码是一个乱码,我们还需要对该代码进行转码,于是要在下面加多一行转码的。
urllib中包括了四个模块,包括
urllib.request,urllib.error,urllib.parse,urllib.robotparser
urllib.request可以用来发送request和获取request的结果
urllib.error包含了urllib.request产生的异常
urllib.parse用来解析和处理URL
urllib.robotparse用来解析页面的robots.txt文件