Crawlspider没有抓取任何内容
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
#scrapy crawl dmoz -o items.json -t json
from scrapy.http import Request
from urlparse import urlparse
from manga.items import MangaItem
class MangaHere(CrawlSpider):
name = "mangahs"
allowed_domains = ["mangahere.com"]
start_urls = ["http://www.mangahere.com/seinen/"]
rules = [Rule(SgmlLinkExtractor(allow = ('//a[@class="next"]')), follow=True,
callback='parse_item'),]
#def parse(self, response):
# get indext depth for every page
# hxs = HtmlXPathSelector(response)
# next_link = hxs.select('//a[@class="next"]')
# index_depth = int(next_link.select('preceding-sibling::a[1]/text()').extract()[0])
#create a request for the first page
# url = urlparse("http://www.mangahere.com/seinen/")
# yield Request(url.geturl(), callback=self.parse_item)
#create a request for each subsequent page in the form "./seinen/x.html"
# for x in xrange(2, index_depth):
# pageURL = "http://www.mangahere.com/seinen/%s.htm" % x
# url = urlparse(pageURL)
# yield Request(url.geturl(), callback=self.parse_item)
def parse_start_url(self, response):
list(self.parse_item(response))
def parse_item(self,response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//ul/li/div')
items = []
for site in sites:
rating = site.select("p/span/text()").extract()
desc = site.select("p[2]/text()").extract()
for i in rating:
for p in desc:
if float(i) > 4.8 and "ecchi" not in str(p):
item = MangaItem()
item['title'] = site.select("div/a/text()").extract()
item['link'] = site.select("div/a/@href").extract()
item['desc'] = site.select("p[2]/text()").extract()
item['rate'] = site.select("p/span/text()").extract()
items.append(item)
return items
这里提到的注释内容是一个在没有使用爬虫蜘蛛的情况下抓取网页的方法,是这里的某位朋友帮我提供的。不过我还是想学会怎么让爬虫蜘蛛正常工作,毕竟了解这些是有益的。
我没有遇到错误,但是抓取到的页面数量是0。我查了很多帖子,听说我需要添加一个 parse_start_url
,但这并没有帮助,改名字的解析函数也没用。
到底哪里出了问题?是我的规则不对,还是我漏掉了什么?
3 个回答
0
你在规则里的回调函数和方法不匹配。CrawlSpider有一个默认的方法叫做parse,所以def parse(CrawlSpider)
应该改成def parse_item
,这样才能和你的回调函数对应上。
1
这里的 allow
应该是用来匹配网址的正则表达式,而不是 xpath
。
如果你想使用 xpath
,那么你需要用 restrict_xpath
。
1
你需要把你的规则改成像这样的:
rules = [Rule(SgmlLinkExtractor(allow = ('/\d+.htm')), follow=True,
callback='parse_item'),]