【问题标题】:want to scrape only text inside <ul> without spaces and balises只想抓取 <ul> 内的文本,没有空格和应答器
【发布时间】:2020-01-06 17:32:45
【问题描述】:

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

我正在使用这段代码,但它从 ul 中带来了空格、换行符和应答器 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

当我添加标签 text()

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

它只刮掉空格。

【问题讨论】:

  • response 是什么?你能举一个你想要的输出的例子吗?

标签: python xpath web-scraping scrapy


【解决方案1】:

发生这种情况是因为您想要的文本不是 &lt;ul&gt; 标记的直接子代,因此使用 /text() 将返回直接子代(或简称为子代)文本。您需要从 &lt;ul&gt; 标签的孙子那里获取文本,这是您要抓取的文本。为此,您可以使用 //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.\n\nS’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.'

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2021-03-12
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多