其实where和what是交融的一体,当你找到what的时候,自然就找到了where。当你确定了where时,what自然而然就知道了。
这次我们爬取诗词名句网 \”http://www.shicimingju.com/\” 的名著,如爬取“三国演义”、“隋唐演义”等。
爬取内容如下:
1.在主页面利用正则爬取小说名字存入book_name,然后再爬取每章的名字存入chapter,爬取每章的链接存入bookurl。
2.使用for循环一一使用bookurl[?]来爬取子页面代码。
3.利用正则将子页面代码中的每章的内容爬出来。

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

A picture is worth a thousand words
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(\'(.*)
\',html,re.S)
chapter=re.findall(\'href=\"/book/.{0,30}\\d\\.html\">(.*?)\',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(\'(.*?)\',chapterHtml,re.S)
#替换其中的标签和 
chapterText=re.sub(\'\',\'\',\'\'.join(chapterText))
chapterText = re.sub(\'
\', \'\', \'\'.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()
书写正则抓取网页信息,存入数据库或文件。