在爬虫之前我们需要有一个清晰的思路,书写爬虫之前的步骤:
1. 从哪爬 where
2. 爬什么 what
3. 怎么爬 how
4. 爬了之后信息如何保存 save
从哪爬where和爬什么what
其实where和what是交融的一体,当你找到what的时候,自然就找到了where。
当你确定了where时,what自然而然就知道了。
这次我们爬取诗词名句网(http://www.shicimingju.com/) 的名著,如爬取“三国演义”、“隋唐演义”等。
爬取内容如下:
主页面 :[小说名字,每章的名字,每章的链接]
若干次页面:[每章的内容]
怎么爬How
1. 在主页面利用正则爬取小说名字存入book_name,然后再爬取每章的名字存入chapter,爬取每章的链接存入bookurl。
2. 使用for循环一一使用bookurl[?]来爬取子页面代码。
3. 利用正则将子页面代码中的每章的内容爬出来。
爬了之后信息如何保存
1. 小说类型适合使用文件保存,不适合数据库存储。
2. 将book_name作为文件名创建,利用for循环读取每章的名字chapter[?]和每章的内容chapterText存入文件,形成一个完整的小说文件。
编写代码
1. 读取网页代码
import urllib.requestimport reindexUrl="http://www.shicimingju.com/book/sanguoyanyi.html"html =urllib.request.urlopen(indexUrl).read()html=html.decode('utf8')
2. 爬取书名book_name,爬取每章的名字chapter,爬取书的链接bookurl。
具体问题需要具体分析,我这里在爬取每章的链接的时候发现竟然是相对路径,无法直接使用,于是只能针对书的链接进行字符串修改,从而来跳转到每章的页面。
book_name=re.findall('<h1>(.*)</h1>',html,re.S)chapter=re.findall('href="/book/.{0,30}\d\.html">(.*?)</a>',html,re.S)bookurl=re.findall('href="(/book/.{0,30}\d\.html)">',html,re.S)chapterUrlBegin=re.sub('.html','',indexUrl)#将书的链接替换成每章的链接开头
3. 爬取每章的内容chapterText,并且输出成文件。
其中要注意看具体的输出,替换其中的一些字符和标签。
for i in range(0,len(bookurl)): #提取每章的number number=re.findall('/(.{1,4})\.html',bookurl[i]) #合并字符串形成每章的链接 chapterUrl=re.sub('$',"/"+number[0]+".html",chapterUrlBegin) #打开链接网页 chapterHtml=urllib.request.urlopen(chapterUrl).read() chapterHtml=chapterHtml.decode('utf-8','ignore') #找到每章内容 chapterText=re.findall('<div id="con2".*?>(.*?)</div>',chapterHtml,re.S) #替换其中的标签<p></p>和  chapterText=re.sub('<p>','',''.join(chapterText)) chapterText = re.sub('</p>', '', ''.join(chapterText)) chapterText = re.sub('', ' ', ''.join(chapterText)) #输出文件 f=open('D://book/'+"".join(book_name)+'.txt','a',encoding='utf-8') f.write(chapter[i]+"\n") f.write(chapterText+"\n") f.close()
这样,名著就爬取成功了。
总的过程就一句话:书写正则抓取网页信息,存入数据库或文件。