Python 网页抓取-我不能使用for循环来列出元素
我目前正在建立一个网页刮板,我遇到了一个问题。 当我试图构建for循环以便按公司重新组合所有信息时,提取会不断地将相同类型的所有元素显示在一起 当我意识到它不起作用时,我返回并尝试只显示第一个元素的索引列表,但即使我键入[0],所有元素都会显示给我,就好像没有进行特定选择一样Python 网页抓取-我不能使用for循环来列出元素,python,for-loop,web-scraping,scrapy,Python,For Loop,Web Scraping,Scrapy,我目前正在建立一个网页刮板,我遇到了一个问题。 当我试图构建for循环以便按公司重新组合所有信息时,提取会不断地将相同类型的所有元素显示在一起 当我意识到它不起作用时,我返回并尝试只显示第一个元素的索引列表,但即使我键入[0],所有元素都会显示给我,就好像没有进行特定选择一样 import scrapy from centech.items import CentechItem class CentechSpiderSpider(scrapy.Spider): name = 'cent
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 ,
}
我希望只看到页面的第一个元素,但所有的企业都会显示出来
谢谢。我不太确定您想要什么样的输出。我猜了一下,修改了你的脚本以获得以下结果。您需要深入一层才能获取完整描述,因为部分描述已被破坏:
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}
您还可以在xpath中添加id来唯一标识它