只想在里面抓取没有<ul>空格和应答器的文本



我正在使用 xpath,我想从这个 URL 中抓取:https://www.le-dictionnaire.com/definition/tout'

我正在使用这段代码,但它带来了来自 ul 的空格、新行和 balises li:

def parse(self, response):
print("procesing:"+response.url)
#Extract data using css selectors
#product_name=response.css('.product::text').extract()
#price_range=response.css('.value::text').extract()
#Extract data using xpath
title = response.xpath("//b/text()").extract()
genre1 = response.xpath("(//span/text())[2]").extract()
def1 = response.xpath("((//*[self::ul])[1])").extract()
genre2 = response.xpath("(//span/text())[3]").extract()
def2 = response.xpath("((//*[self::ul])[2])").extract()
row_data=zip(title,genre1,def1,genre2,def2)
#Making extracted data row wise
for item in row_data:
#create a dictionary to store the scraped info
scraped_info = {
#key:value
'page':response.url,
'title' : item[0], #item[0] means product in the list and so on, index tells what value to assign
'genere1' : item[1],
'def1' : item[2],
'genere2' : item[3],
'def2' : item[4],
}
#yield or give the scraped info to scrapy
yield scraped_info

当我添加标签文本((

def1 = response.xpath("((//*[self::ul])[1]/text())").extract()
def2 = response.xpath("((//*[self::ul])[2]/text())").extract()

它只抓取空格。

发生这种情况是因为您想要的文本不是<ul>标签的直接子级,因此使用/text()将返回直接子项(或只是子项(文本。您需要从<ul>标签的孙子那里获取文本,这是您要抓取的文本。为此,您可以使用//text()而不是/text或缩小 XPath 表达式的范围,如下所示:

"//*[@class='defbox'][n]//ul/li/a/text()"

通过这样做,您可以获得更清晰的列表输出,也可以制作一个干净的字符串:

>>> def1 = response.xpath("//*[@class='defbox'][1]//ul/li/a/text()").getall()
>>> ' '.join(def1)
'Qui comprend l’intégrité, l’entièreté, la totalité d’une chose considérée par rapport au nombre, à l’étendue ou à l’intensité de l’énergie.nnS’emploie devant un nom précédé ou non d’un article, d’un dé
monstratif ou d’un possessif. S’emploie aussi devant un nom propre. S’emploie également devant ceci, cela, ce que, ce qui, ceux qui et celles qui. S’emploie aussi comme attribut après le verbe.'

最新更新