【问题标题】:Scrapy different number of url returnScrapy不同数量的url返回
【发布时间】:2014-05-19 16:28:49
【问题描述】:

我已经构建了一个爬虫来抓取固定域中的内容,并提取与修复正则表达式匹配的 url。如果看到一个特定的 url,爬虫就会跟随这个链接。爬虫可以完美地提取 url,但是每次我运行爬虫时,它都会返回不同数量的链接,即每次运行时链接的数量都不同。我正在使用 Scrapy 进行爬网。这是scrapy的问题吗?代码是:

class MySpider(CrawlSpider):
   name = "xyz"
   allowed_domains = ["xyz.nl"]
   start_urls = ["http://www.xyz.nl/Vacancies"] 
   rules = (Rule(SgmlLinkExtractor(allow=[r'\/V-\d{7}\/[\w\S]+']), callback='parse_item'),Rule(SgmlLinkExtractor(allow=[r'\?page\=\d+\&sortCriteria\=1']), follow=True),)



 def parse_item(self, response):

  outputfile = open('urllist.txt','a')
  print response.url
  outputfile.write(response.url+'\n')

【问题讨论】:

  • 像往常一样:请输入代码?
  • @sshashank124 你去!!

标签: python scrapy


【解决方案1】:

不要在parse_item()方法中手动编写链接并使用a模式打开文件,而是使用scrapy内置的item exporters。定义一个带有链接字段的项目:

from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field


class MyItem(Item):
    url = Field()


class MySpider(CrawlSpider):
    name = "xyz"
    allowed_domains = ["xyz.nl"]
    start_urls = ["http://www.xyz.nl/Vacancies"]
    rules = (Rule(SgmlLinkExtractor(allow=[r'\/V-\d{7}\/[\w\S]+']), callback='parse_item'),
             Rule(SgmlLinkExtractor(allow=[r'\?page\=\d+\&sortCriteria\=1']), follow=True),)

    def parse_item(self, response):
        item = MyItem()
        item['url'] = response.url
        yield item

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    相关资源
    最近更新 更多