获取元素属性值的CSS选择器

14 投票
2 回答
26360 浏览
提问于 2025-04-18 14:59

HTML的结构是这样的:

<td class='hey'> 
<a href="https://example.com">First one</a>
</td>

这是我的选择器:

m_URL = sel.css("td.hey a:nth-child(1)[href] ").extract()  

现在我的选择器会输出 <a href="https://example.com">First one</a>,但我只想要它输出链接本身:https://example.com

我该怎么做呢?

2 个回答

6

你可以试试这个:

m_URL = sel.css("td.hey a:nth-child(1)").xpath('@href').extract()
26

标签中获取::attr(value)

示例(使用Scrapy shell):

$ scrapy shell index.html
>>> response.css('td.hey a:nth-child(1)::attr(href)').extract()
[u'https://example.com']

这里的index.html包含:

<table>
    <tr>
        <td class='hey'>
            <a href="https://example.com">Fist one</a>
        </td>
    </tr>
</table>

撰写回答