【问题标题】:Python Scrapy can't extract text from classPython Scrapy 无法从类中提取文本
【发布时间】:2014-03-01 18:47:42
【问题描述】:

请看这段 html 代码:

<header class="online">
                        <img src="http://static.flv.com/themes/h5/img/iconos/online.png"> <span>online</span> 
            <img src="http://static.flv.com/themes/h5/img/iconos/ojo16.png"> 428                        <p>xxfantasia</p>
</header>

我想获取里面的文本(在本例中为 428)。我用这个:

        def parse(self, response):
            sel = Selector(response)
            cams = sel.css('header.online')
            for cam in cams:
                  print cam.css('text').extract()

我认为我使用了正确的 css 选择器,但结果为空。

有什么帮助吗?

【问题讨论】:

    标签: python css python-2.7 css-selectors scrapy


    【解决方案1】:

    CSS 选择器don't normally have syntax to extract text content.

    但是 Scrapy 使用 ::text 伪元素扩展了 CSS 选择器,所以你想使用 cam.css('::text').extract() 应该给你同样的东西 cam.xpath('.//text()').extract()

    注意:Scrapy 还添加了 ::attr(attribute_name) 功能性伪元素来提取属性值(这对于标准 CSS 选择器也是不可能的)

    【讨论】:

    • 使用cam.css('header.online::text').extract() 结果如下:[u' \n ', u' 428 ', u'\n '] 我怎么才能只得到[u'428']
    • 可以使用 Python 的 strip()filter() 方法,例如:filter(bool, [e.strip() for e in cam.css('header.online::text').extract()])
    • 完美运行。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2014-10-30
    • 2021-05-12
    相关资源
    最近更新 更多