有了爬虫的基础知识,接下来爬取笔趣阁网站小说作为练手。《剑来》是我比较喜欢的一本小说,很值得一看。目前小说还没完结,笔趣阁只更新了603章,因此就凑整数爬取前600章节。
网站结构的分析
从笔趣阁目录页可以看到,要爬取每一个章节的内容需要获取每一个章节的地址。每一个章节的地址都在“http://www.biquduge.com/12_12785/”这个目录下后面再添加后续7位数字的页码,这些页码没有一定的规律,因此爬取每一章节的页码,写入文件。这里为什么要写入文件,是为了后续用多线程进行爬虫。
#爬取http://www.biquduge.com/12_12785/首页中每一章节的地址
r = requests.get('http:/www.biquduge.com/12_12785/',headers=header,timeout=10)
soup = BeautifulSoup(r.text,'lxml')
lis = soup.find('div',id='list')
content = lis.find_all('a')
for item in content:
if item.string == None:
continue
else:
with open(r'd:\ip.text','a+',encoding='utf-8') as f:
f.write(item.get("href")+'\n')
with open(r'd:\ip.text','r') as f:
for i in range(600):
line = f.readline().strip('\n')
link_add.append(link+line)
i+=1
f.close()
爬取小说内容
小说内容分为章节名称和每一章节的正文,有之前学习的基础也比较容易可以完成简单爬虫代码。
for i in range(600):
r = requests.get(link_add[i],headers=header,timeout=30)
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text,'lxml')
chapter = soup.find('div',class_='bookname').find('h1')
article = soup