【问题标题】:How to scrape 2 web page with same domain on scrapy using python?如何使用python在scrapy上抓取2个具有相同域的网页?
【发布时间】:2019-04-03 06:59:08
【问题描述】:

大家好,我是抓取数据的新手,我已经尝试过基本的。但我的问题是我需要抓取 2 个具有相同域的网页

我的逻辑是, 第一页www.sample.com/view-all.html *此页面打开所有项目列表,我需要获取每个项目的所有href attr。

第二页www.sample.com/productpage.52689.html

*这是来自第一页的链接,所以 52689 需要根据第一页提供的链接动态更改。

我需要在第二页获取所有数据,如标题、描述等。

我在想的是 for 循环,但它对我不起作用。我在谷歌上搜索,但没有人和我有同样的问题。请帮帮我

import scrapy

class SalesItemSpider(scrapy.Spider):
    name = 'sales_item'
    allowed_domains = ['www.sample.com']
    start_urls = ['www.sample.com/view-all.html', 'www.sample.com/productpage.00001.html']

    def parse(self, response):
        for product_item in response.css('li.product-item'):
            item = {
                'URL': product_item.css('a::attr(href)').extract_first(),
            }
            yield item`

【问题讨论】:

  • Scrapy 不必yield 项目。它可以yieldRequest() 带有 url 和函数名称,这将从这个 url 中抓取。这样parse 可以从主页抓取网址并使用Request() 运行其他功能以从这些网址中抓取。您应该拥有所有文档 - docs.scrapy.org - 如果您对抓取感兴趣,那么您应该从第一页到最后一页阅读此文档。

标签: python web-scraping scrapy


【解决方案1】:

parse 中,您可以通过yield Request() 使用url 和函数名在不同的函数中抓取该url

def parse(self, response):

    for product_item in response.css('li.product-item'):
        url = product_item.css('a::attr(href)').extract_first() 

        # it will send `www.sample.com/productpage.52689.html` to `parse_subpage` 
        yield scrapy.Request(url=url, callback=self.parse_subpage)


def parse_subpage(self, response):
    # here you parse from www.sample.com/productpage.52689.html 

    item = {
        'title': ..., 
        'description': ...
    }

    yield item

Scrapy documentationits tutorial 中查找Request


还有

response.follow(url, callback=self.parse_subpage)

它会自动将www.sample.com 添加到网址中,这样您就不必在

Request(url = "www.sample.com/" + url, callback=self.parse_subpage)

A shortcut for creating Requests


如果您对抓取感兴趣,那么您应该阅读docs.scrapy.org 从第一页到最后一页。

【讨论】:

  • 谢谢@furas,一切正常我已经阅读了文档并了解了这些功能。我已经更改了您提供的代码中的一些内容,现在可以正常工作了,谢谢
猜你喜欢
  • 2019-11-16
  • 1970-01-01
  • 2018-03-08
  • 2018-02-06
  • 2021-01-13
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多