我无法让蜘蛛跟随广告的下一页而不关注它找到的每个链接,最终返回每个craigslist页面。我已经玩过规则,因为我知道这就是问题所在,但我要么只是第一页,每个页面都在craigslist上,或者什么都没有。有什么帮助吗?
这是我目前的代码:
from scrapy.selector import HtmlXPathSelector
from craigslist_sample.items import CraigslistSampleItem
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.http import Request
class PageSpider(CrawlSpider):
name = "cto"
allowed_domains = ["medford.craigslist.org"]
start_urls = ["http://medford.craigslist.org/cto/"]
rules = (
Rule(
SgmlLinkExtractor(allow_domains=("medford.craigslist.org", )),
callback='parse_page', follow=True
),
)
def parse_page(self, response):
hxs = HtmlXPathSelector(response)
rows = hxs.select('//div[@class="content"]/p[@class="row"]')
for row in rows:
item = CraigslistSampleItem()
link = row.xpath('.//span[@class="pl"]/a')
item['title'] = link.xpath("text()").extract()
item['link'] = link.xpath("@href").extract()
item['price'] = row.xpath('.//span[@class="l2"]/span[@class="price"]/text()').extract()
url = 'http://medford.craigslist.org{}'.format(''.join(item['link']))
yield Request(url=url, meta={'item': item}, callback=self.parse_item_page)
def parse_item_page(self, response):
hxs = HtmlXPathSelector(response)
item = response.meta['item']
item['description'] = hxs.select('//section[@id="postingbody"]/text()').extract()
return item
答案 0 :(得分:1)
您应指定SgmlLinkExtractor的allow
参数:
允许(正则表达式(或列表)) - 单个常规 表达式(或正则表达式列表)(绝对)URL 必须匹配才能被提取。如果没有给(或空),它会 匹配所有链接。
rules = (
Rule(SgmlLinkExtractor(allow='http://medford.craigslist.org/cto/'),
callback='parse_page', follow=True),
)
这会将所有链接保留在http://medford.craigslist.org/cto/
网址
希望有所帮助。