【问题标题】:Scrapy: Scraping nested linksScrapy:抓取嵌套链接
【发布时间】:2017-07-26 22:12:16
【问题描述】:

我是 Scrapy 和网络抓取的新手。请不要生气。我正在尝试抓取 profilecanada.com。现在,当我运行下面的代码时,没有给出错误,但我认为它仍然没有抓取。在我的代码中,我试图从一个有链接列表的页面开始。每个链接都指向一个页面,其中还有另一个链接列表。从该链接是另一个页面,其中包含我需要提取并保存到 json 文件中的数据。一般来说,它类似于“嵌套链接抓取”。我不知道它实际上是怎么称呼的。当我咆哮时,请参阅下图了解蜘蛛的结果。提前感谢您的帮助。

import scrapy

class ProfilecanadaSpider(scrapy.Spider):
    name = 'profilecanada'
    allowed_domains = ['http://www.profilecanada.com']
    start_urls = ['http://www.profilecanada.com/browse_by_category.cfm/']

    def parse(self, response):

      # urls in from start_url
      category_list_urls =  response.css('div.div_category_list > div.div_category_list_column > ul > li.li_category > a::attr(href)').extract()
      # start_u = 'http://www.profilecanada.com/browse_by_category.cfm/'

      # for each category of company
      for url in category_list_urls:
        url = url[3:]
        url = response.urljoin(url)
        return scrapy.Request(url=url, callback=self.profileCategoryPages)


    def profileCategoryPages(self, response):
      company_list_url = response.css('div.dv_en_block_name_frame > a::attr(href)').extract()

      # for each company in the list
      for url in company_list_url:
        url = response.urljoin(url)
        return  scrapy.Request(url=url, callback=self.companyDetails)

    def companyDetails(self, response):
      return {
        'company_name': response.css('span#name_frame::text').extract_first(),
        'street_address': str(response.css('span#frame_addr::text').extract_first()),
        'city': str(response.css('span#frame_city::text').extract_first()),
        'region_or_province': str(response.css('span#frame_province::text').extract_first()),
        'postal_code': str(response.css('span#frame_postal::text').extract_first()),
        'country': str(response.css('div.type6_GM > div > div::text')[-1].extract())[2:],
        'phone_number': str(response.css('span#frame_phone::text').extract_first()),
        'fax_number': str(response.css('span#frame_fax::text').extract_first()),
        'email': str(response.css('span#frame_email::text').extract_first()),
        'website': str(response.css('span#frame_website > a::attr(href)').extract_first()),
      }

CMD 中的图像结果: The result in cmd when I ran the spider

【问题讨论】:

    标签: web-scraping scrapy scrapy-spider


    【解决方案1】:

    您应该将allowed_domains 更改为allowed_domains = ['profilecanada.com'] 并将所有return scrapy.Request 更改为yield scrapy.Request 并且它会开始工作,请记住,遵守 robots.txt 并不总是足够的,如果出现以下情况,您应该限制您的请求必要的。

    【讨论】:

    • “请记住,遵守 robots.txt 并不总是足够的,您应该在必要时限制您的请求”是什么意思?
    • 我按照你说的做了,而且确实有效。然后,当我再次运行它时,它现在使用不同的 url 将我重定向到另一个网页
    • 嘿@RejeenaldFlores 这意味着有些网站使用多种反机器人技术来阻止您提取数据,其中一些包括重定向或验证码,甚至将您列入黑名单,他们在请求中检测到一些异常行为
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多