经过一天的学习, 终于写出了自己的第一个完整的爬虫, 虽然还是有一些瑕疵, 先放上代码, 后期再进行整理说明和更新。
代码很简单,用来爬取小说站点的一本小说并分章节进行保存。
== 首次更新:2020年2月5日 零点十八分 ==
#此代码用于实验爬虫爬取小说站点小说
import requests
import re
import time
import os
def get_section_list(get_url): #获取书籍章节列表函数
response=requests.get(get_url)
response.encoding='gbk'
html=response.text
#以下三行注释掉的代码因为页面结构的原因,所以写了三个结构, 后面解释。
#zhangjie0=re.findall('<a title=".*?href="(.*?)">.*?-->\r\n (.*?)</a>',html,re.S) #0-4-8
#zhangjie1 = re.findall(' /><a href="(.*?)".*?title=".*?">(.*?)</a>', html, re.S) #1-5-9
#zhangjie2 = re.findall('/><a href="http://(.*?)" title=".*?>(.*?)</a> </div>', html, re.S) #2-6-10
zhangjie3 = re.findall('<a href="/(.*?)" title=".*?-->\r\n (.*?)</a> </li>', html, re.S) #3-7-11
#return zhangjie0,zhangjie1,zhangjie2,zhangjie3
return zhangjie3
book_url='http://www.kuuhu.com/xiaoshuo/288/288042/index.html'
section_list=get_section_list(book_url) #获取列表
#--------------内容函数
def get_content(url,name):
content_res = requests.get(url)
content_res.encoding = 'gbk'
html = content_res.text
title = re.findall('<h1>(.*?)</h1>', html, re.S)
content = re.findall(' (.*?)<br />', html, re.S)
path1="d:/book_download/"+name+".txt" #以章节名命名文件名
f = open(path1, "a") #创建文件,并写入章节内容
f.write(title[0] + "\n\n")
for i in content:
f.write(i + "\n")
f.close()
#内容函数结束
f=open("d:/book/mulu.txt","a")
for i in section_list:
a=i[1]
b=a.replace('?','')
#print(b)
get_content('http://www.kuuhu.com/'+i[0],b)
time.sleep(2)
#f.write(i[0]+"\n")
#f.write(i[1]+"\n")
print(i[0])
print(i[1])
- 爬取的结果: