我有以下CrawlSpider,我无法关注大学网站上的链接。我认为这是因为不稳定的标记,但我不确定。我试图添加一条规则,但它不会跟随。我怎样才能做到这一点?
它可以作为单页蜘蛛使用,并且可以抓取第1页,但不会关注链接。
注意,不是家庭作业,只是我在玩,并得到了刮掉Dmoz的板子。感谢所有帮助。
# -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from example.items import ExampleItem
class ExampleSpider(CrawlSpider):
name = "example"
allowed_domains = ["example.ac.uk"]
start_urls = (
'http://www.example.ac.uk/courses/course-finder?query=&f.Year_of_entry|E=2015/16&f.Type|D=Undergraduate',
''
)
rules = (Rule (SgmlLinkExtractor(allow=("index\.php", ), callback="parse"),))
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//div[@id="course_list"]')
items = []
for site in sites:
item = ExampleItem()
item['link'] = site.xpath('//h2/a/@href').extract()
item['name'] = site.xpath('//h2/a/text()').extract()
items.append(item)
return items
网站上的分页标记如下:
<div class="pagination">
<ul>
<li><i class="fa fa-chevron-left"></i><span>Previous</span></li>
<li><span>Go to page</span> 1</li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=11"><span>Go to page</span> 2</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=21"><span>Go to page</span> 3</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=31"><span>Go to page</span> 4</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=41"><span>Go to page</span> 5</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=51"><span>Go to page</span> 6</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=61"><span>Go to page</span> 7</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=71"><span>Go to page</span> 8</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=81"><span>Go to page</span> 9</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=91"><span>Go to page</span> 10</a></li>
<li><a href="course-finder?query=&fYear_of_entryE=2015/16&fTypeD=Undergraduate&start_rank=11"><i class="fa fa-chevron-right"></i><span>Next</span></a></li>
</ul>
</div>
答案 0 :(得分:2)
至少你遇到的第一个问题是你在链接提取器中定义callback
,但应该在规则级别定义:
rules = (
Rule(LinkExtractor(allow=("index\.php", )), callback="parse_result"),
)
def parse_result(self, response):
...
此外,您需要一个单独的规则来跟随分页:
rules = (
Rule(LinkExtractor(allow=("index\.php", )), callback="parse_result"),
Rule(LinkExtractor(restrict_xpaths='//div[@class="pagination"]'), follow=True),
)