CSS Selector获取元素属性值

use*_*364 8 python css-selectors scrapy web-scraping

HTML结构是这样的:

<td class='hey'> 
<a href="https://example.com">First one</a>
</td>
Run Code Online (Sandbox Code Playgroud)

这是我的选择器:

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

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

我怎样才能做到这一点?

ale*_*cxe 17

::attr(value)a标签中获取.

演示(使用Scrapy shell):

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

其中index.html包括:

<table>
    <tr>
        <td class='hey'>
            <a href="https://example.com">Fist one</a>
        </td>
    </tr>
</table>
Run Code Online (Sandbox Code Playgroud)


kin*_*rcy 6

你可以试试这个:

m_URL = sel.css("td.hey a:nth-child(1)").xpath('@href').extract()
Run Code Online (Sandbox Code Playgroud)