终于将一本书的小说爬虫完善了。在这里我爬取的是“去看看小说网”中的“剑来”一书。
代码中关于爬取内容的地方,读者可参考,然后按照自己想要爬取的网页进行修改。
(以下代码为完整代码,已测试)
#-*- coding=utf-8 -*-
import urllib2
import urlparse
import Queue
import time
from bs4 import BeautifulSoup
# s1 = '大家好啊'
# open('hello.txt','w').write(s1)
# 得到小说内容
def link_crawler(seed_url):
firstTitle = BeautifulSoup(download(seed_url)).title.text.split('(')[0] # 拿到小说名字
filename = firstTitle+'.txt'
file = open(filename,'w+') # 创建以小说名为名的txt文件,并将文件设置为追加模式
file.write(firstTitle+'\n\n')
# print firstTitle
crawler_queue = Queue.deque([seed_url]) # 将链接存到crawler_queue列表中,并且按照降序存放
seen = set(crawler_queue) # 将访问过的链接存放在seen中
while crawler_queue:
url = crawler_queue.pop() # 提取第一个链接
html = download(url)
# soup = BeautifulSoup(html)
soup = BeautifulSoup(html).find_all('dd',{'class':'col-md-3'})
# print soup
for link in soup: