python - Scrapy嵌套页面爬取

标签 python scrapy

我正在为嵌套页面抓取而苦苦挣扎。

我只得到与第一个抓取页面项目数一样多的项目。

站点结构将是这样的。

  1. 抓取品牌 - 品牌链接
  2. 使用品牌链接去抓取模型和模型链接
  3. 使用模型链接去抓取特定公告及其属性。

假设品牌 A 有 2 个模型,第一个模型有 11 个公告,第二个模型有 9 个。品牌 B 有 3 个模型,每个模型有 5 个公告。

在上面的示例中,我需要将每个公告作为单独的项目(总共 35 个)获取,但我不是这样获取项目编号,例如品牌 A 和第一个公告,然后是品牌 B 和第一个公告。

class SiteSpider(CrawlSpider):
log.start(logfile="log.txt", loglevel="DEBUG", logstdout=None)
name = "site"
#download_delay = 2
allowed_domains = ['site.com']
start_urls = ['http://www.site.com/search.php?c=1111']
items = {}


def parse(self, response):
    sel = Selector(response)
    #requests =[]
    brands = sel.xpath("//li[@class='class_11']")
    for brand in brands:
        item = SiteItem()
        url = brand.xpath('a/@href')[0].extract()
        item['marka'] = brand.xpath("a/text()")[0].extract()
        item['marka_link'] =  brand.xpath('a/@href')[0].extract()
        request = Request("http://www.site.com"+url,callback=self.parse_model, meta={'item':item})
        # requests.append(request)
        #
        yield request

def parse_model(self, response):
    sel = Selector(response)
    models = sel.xpath("//li[@class='class_12']")
    for model in models:

        item = SiteUtem(response.meta["item"])
        url2 = model.xpath('a/@href')[0].extract()
        item ['model'] = model.xpath("a/text()")[0].extract()
        item ['model_link'] = url2

    return item

你能用伪代码帮助这个菜鸟实现这个吗?我猜我在基础层面犯了一个错误。

最佳答案

在您的 parse_model 中,您有一个创建项目但不产生项目的循环,请尝试将其更改为:

def parse_model(self, response):
    sel = Selector(response)
    models = sel.xpath("//li[@class='class_12']")
    for model in models:

        item = SiteUtem(response.meta["item"])
        url2 = model.xpath('a/@href')[0].extract()
        item ['model'] = model.xpath("a/text()")[0].extract()
        item ['model_link'] = url2

        yield item

关于python - Scrapy嵌套页面爬取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21376834/

相关文章:

python - Scrapy crawl命令输出如何保存

python - Incapsula 的工作原理以及如何战胜它

macos - 在 Mac OSX 10.9.5 上安装 Scrapy

python - 如何在 anaconda 中升级 scikit-learn 包

python - 将 panda 系列更改为 int

python - 使用 numpy.argwhere 获取 np.array 中的匹配值

python - 为什么我在尝试运行 Python 脚本时得到 "expected an indented block"?

python - ConfigParser 和 2 个配置文件

scrapy - 如何在 scrapy 中使用 python 请求?

python - 为 scrapy CrawlSpider 的方法创建单元测试