scrapy无法抓取craigslist

时间:2013-02-07 15:46:07

标签: scrapy rules web-crawler

此相同的代码抓取黄皮书没有问题和预期。将规则更改为CL,然后点击第一个网址,然后在没有相关输出的情况下摇摇欲坠。

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from craigs.items import CraigsItem

class MySpider(CrawlSpider):
        name = "craigs"
        allowed_domains = ["craiglist.org"]

        start_urls = ["http://newyork.craigslist.org/cpg/"]

        rules = [Rule(SgmlLinkExtractor(restrict_xpaths=('/html/body/blockquote[3]/p/a',)), follow=True, callback='parse_profile')]

        def parse_profile(self, response):
                found = []
                img = CraigsItem()
                hxs = HtmlXPathSelector(response)
                img['title'] = hxs.select('//h2[contains(@class, "postingtitle")]/text()').extract()
                img['text'] = hxs.select('//section[contains(@id, "postingbody")]/text()').extract()
                img['tags'] =  hxs.select('//html/body/article/section/section[2]/section[2]/ul/li[1]').extract()

                print found[0]
                return found[0]

这是输出http://pastie.org/6087878 正如您所看到的,抓取第一个网址没有问题http://newyork.craigslist.org/mnh/cpg/3600242403.html> 但后来就死了。

我可以使用CLI并转储所有链接,例如此SgmlLinkExtractor(restrict_xpaths =('/ html / body / blockquote [3] / p / a',))。extract_links(response)with xpaths或keyword SgmlLinkExtractor(allow = R '/ CPG /.+')。extract_links(响应)
输出 - > http://pastie.org/6085322

但在抓取过程中,同一查询失败。 WTF ??

1 个答案:

答案 0 :(得分:3)

如果查看文档,您会看到

  

allowed_domains包含域的字符串的可选列表   允许这只蜘蛛爬行。对不属于的URL的请求   如果,则不会遵循此列表中指定的域名   OffsiteMiddleware已启用。

您允许的域名

 allowed_domains = ["craiglist.org"]

但您正在尝试获取子域

02-07 15:39:03+0000 [craigs] DEBUG: Filtered offsite request to 'newyork.craigslist.org': <GET http://newyork.craigslist.org/mnh/cpg/3600242403.html>

这就是它被过滤的原因

从您的抓取工具中删除allowed_domains,在其中添加适当的域名,以避免过滤的异地请求