【问题标题】:CSS Selector to get the element attribute valueCSS Selector 获取元素属性值
【发布时间】:2014-09-19 04:22:36
【问题描述】:

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()  

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

我该怎么做?

【问题讨论】:

    标签: python css-selectors web-scraping scrapy


    【解决方案1】:

    你可以试试这个:

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

    【讨论】:

    • 所以css不能不做吗?因为我是用xpath写的。并想练习如何翻译成css
    【解决方案2】:

    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>
    

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 2014-08-31
      • 2017-08-13
      • 2019-09-09
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多