首页 > 解决方案 > 使用类(Scrapy)在锚标记内查找文本的 Xpath

问题描述

我正在尝试使用 Xpath 提取 Anchor Tag 的链接

网址

<a class="text size-1x-small font-accent color-brand all-caps"
   href="http://time.com/section/business" 
   data-reactid="199">
       Business
</a>

代码

item["category"] = str(
    response.xpath(
        '//a[@class="text size-1x-small font-accent color-brand all-caps"]/text()'
    ).extract()
    )

和python函数

def parseSave(self, response):
    item = NYtimesItem()
    item["category"] = response.xpath(
        '//a[@class="text size-1x-small font-accent color-brand all-caps"]/text()'
    ).extract()

    yield item

请告诉我我做错了什么预期的输出将是锚标签的文本。例如商业

标签: pythonxpathscrapy

解决方案


/text()旨在获取元素的内部文本。要提取 href 属性,请/@href改用。

这是一个方便的 xpath 备忘单


推荐阅读