python - 关于scrapy的使用
本文介绍了python - 关于scrapy的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
用scrapy爬了一下小说网站,spider中的函数单个执行能正确输出,但是调用命令scrapy crawl novel -o novel.csv时却不能抓取任何数据,希望指点一下。以下是文件链接:
http://pan.baidu.com/s/1skOfLJR
mydict文件是对spider中的单个函数测试输出,显示都能正确输出。
解决方案
仔细看看一看, 默认的方法可能用错了,应该为start_requests ,和修改了一些bug,就可能爬了,以下是修改后的源代码!
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import scrapy
from diandian.items import diandianitem
from scrapy.http import Request
class myspider(scrapy.Spider):
name = 'novel'
allowed_domain = ['23wx.com']
def start_requests(self):
for i in range(1,11):
url = 'http://www.23wx.com/class/{}_1.html'.format(i)
yield Request(url,callback=self.getallurl)
#得到每个类别的url
def getallurl(self,response):
id = BeautifulSoup(response.body, 'lxml').select('.first')[0]['href'].split('_')[0].split('/')[-1]
maxnumber = BeautifulSoup(response.body, 'lxml').select('.last')[0].text
for j in range(1, int(maxnumber) + 1):
url = 'http://www.23wx.com/class/{}_{}.html'.format(id, j)
yield Request(url, callback=self.getdetail_url)
# 得到每个类别所有页数的url
def getdetail_url(self,response):
for each in BeautifulSoup(response.body, 'lxml').find_all(bgcolor="#FFFFFF"):
detailurl = each.find_all('td', class_='L')[0].find_all('a')[0]['href']
yield Request(detailurl,callback=self.parse)
#得到具体每个小说的url
def parse(self, response):
items = diandianitem()
soup = BeautifulSoup(response.body,'lxml')
items['name'] = soup.select('#content dd h1')[0].text.split(' ')[0]
t1 = soup.find_all('table', cellspacing="1")[0].find_all('tr')[0]
items['category'] = t1.find_all('a')[0].text
items['author'] = t1.find_all('td')[1].text.strip()
items['condition'] = t1.find_all('td')[2].text.strip()
t2 = soup.find_all('table', cellspacing="1")[0].find_all('tr')[1]
items['save'] = t2.find_all('td')[0].text.strip()
items['length'] = t2.find_all('td')[1].text.strip()
items['last_updated'] = t2.find_all('td')[2].text.strip()
yield items
#得到小说的具体信息
这篇关于python - 关于scrapy的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文