簡體   English   中英

在 scrapy 上更正 Xpath

[英]Correct Xpath for on scrapy

我只想使用 Xpath 從category中獲取數據

頁面鏈接: https://onepagelove.com/3wcc

這是我的 output:

 ['Digital Product', ',', 'Finance', ',', 'Landing Page', ',', 'Thaleah Fat', ',', '23 Feb 2022 by', 'Rob Hope']}

這是網頁中的數據示例:

在此處輸入圖像描述

這是我的代碼:

from scrapy.http import Request
import scrapy
class PushpaSpider(scrapy.Spider):
    name = 'pushpa'
    
    start_urls = ['https://onepagelove.com/inspiration']
    

    def parse(self, response):
        books = response.xpath("//div[@class='thumb-image']//a//@href").extract()
        for book in books:
            absolute_url = response.urljoin(book)
            yield Request(absolute_url, callback=self.parse_book)

    def parse_book(self, response):
        coordinate = response.xpath("//div[@class='inspo-links']//span[2]//text()").getall()
        coordinate = [i.strip() for i in coordinate]
        # remove empty strings:s
        coordinate = [i for i in coordinate if i]
        yield{
            'category':coordinate
            }
      

該網站在 header 內有多個inspo-links ,因此您正在從許多不同類型的數據中提取。

Xpath版本:

def parse_book(self, response):
    xpath_coordinate = response.xpath(
        "//span[@class='link-list']")[1].xpath("a/text()").extract()
    yield {
        'category': xpath_coordinate
    }

CSS 版本:

def parse_book(self, response):
    content = response.css('div.review-content')
    coordinate = header.css("span.link-list")[1].css("a::text").extract()
    yield {
        'category': coordinate
    }

這里的這個片段將只為您提供類別。

在您的圖片示例中,它會給您 ["Experimental", "Informational"]

注意:在您的主要方法中,您獲得了一個非書籍且沒有類別的額外鏈接,scrapy 會自動處理錯誤,因此您仍然可以獲得完整的 output。

這是一個 Xpath 示例,它從圖像中獲取所有 3 種類型的數據:

def parse_book(self, response):
    xpath_coordinate = response.xpath(
        "//span[@class='link-list']")
    features = xpath_coordinate[0].xpath("a/text()").extract()
    category = xpath_coordinate[1].xpath("a/text()").extract()
    typeface = xpath_coordinate[2].xpath("a/text()").extract()
    yield {
        'feature': features,
        'category': category,
        'typeface': typeface
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM