我不能用for循环来列出elemen

2024-05-16 13:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在建设一个网页刮板,我遇到了一个问题。 当我试图构建for循环,以便按公司重新组合所有信息时,抽取会不断地将相同类型的所有元素显示在一起。你知道吗

当我意识到它不起作用时,我返回并尝试只显示第一个元素的索引列表,但即使我键入[0],所有的元素都会显示给我,好像没有做任何特定的选择

import scrapy
from centech.items import CentechItem

class CentechSpiderSpider(scrapy.Spider):
    name = 'centech_spider'
    start_urls = ['https://centech.co/nos-entreprises/']

    def parse(self, response):
       items = CentechItem()
       all_companies = response.xpath("//div[@class = 'fl-post-carousel- 
    post']")[1]    #   "//div[@class = 'fl-post-carousel-post']")[1]
    Nom = all_companies.xpath("//h2[contains(@class, 'fl-post-carousel- 
    title')]/text()").extract()
    Description = all_companies.xpath("//div[contains(@class, 
    'description')]/p/text()").extract()
    # Nom = all_companies.response.css("h2.fl-post-carousel- 
    title::text").extract()
    # Description = all_companies.xpath("p::text").extract()

    yield {'Nom' : Nom ,
           'Description' : Description ,
           }

我只希望看到页面的第一个元素,但所有的企业都会显示出来。你知道吗

谢谢你。你知道吗


Tags: textdiv元素responseextractdescriptionallpost
1条回答
网友
1楼 · 发布于 2024-05-16 13:20:20

我不太确定你想要什么样的结果。我猜了一下,修改了你的脚本,得到了以下结果。您需要深入一层才能获取完整的描述,因为有些描述已损坏:

import scrapy

class CentechSpiderSpider(scrapy.Spider):
    name = 'centech_spider'
    start_urls = ['https://centech.co/nos-entreprises/']

    def parse(self, response):
        for item in response.css("a.fl-post-carousel-link"):
            nom = item.css(".description > h2.fl-post-carousel-title::text").get()
            description = item.css(".description > p::text").get()
            yield {'nom':nom,'description':description}

相关问题 更多 >