爬虫Python玩耍Python

5.Python3爬虫入门实践——爬取名著

2016-07-25  本文已影响2577人  KaelQ

1.准备工作

1.1 从哪爬where和爬什么what

1.2 怎么爬How

1.在主页面利用正则爬取小说名字存入book_name,然后再爬取每章的名字存入chapter,爬取每章的链接存入bookurl。
2.使用for循环一一使用bookurl[?]来爬取子页面代码。
3.利用正则将子页面代码中的每章的内容爬出来。

A picture is worth a thousand words

1.3 爬了之后信息如何保存

1.小说类型适合使用文件保存,不适合数据库存储。
2.将book_name作为文件名创建,利用for循环读取每章的名字chapter[?]和每章的内容chapterText存入文件,形成一个完整的小说文件。

A picture is worth a thousand words

2.编写代码

import urllib.request
import re
indexUrl="http://www.shicimingju.com/book/sanguoyanyi.html"
html =urllib.request.urlopen(indexUrl).read()
html=html.decode('utf8')
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)#将书的链接替换成每章的链接开头
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>和&nbsp
    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()

3.总结

书写正则抓取网页信息,存入数据库或文件。

上一篇 下一篇

猜你喜欢

热点阅读