python - CSS Selector 获取元素属性值

标签 python css-selectors web-scraping scrapy

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 .

我该怎么做?

最佳答案

a 标签中获取 ::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>

关于python - CSS Selector 获取元素属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987480/

相关文章:

python - 遍历圣人中矩阵的行

python - 并发 future 以非阻塞方式将任务提交到进程池

jquery - 需要css转js实现

css - 如何将 css 规则基于 dir 属性的继承值

python - 使用 Selenium (Python) 提取图像

python - 已部署 Azure 函数但从未在 blob 输入上运行

python - 如何将元素列表分组成对?

css - 嵌套在 css :not() selectors 中

python - 如何在要抓取的 url 列表中安全地执行多线程?

google-chrome - 如何在Chrome中提取 "inspect element"部分中的代码?