【问题标题】:Scrapy: how to get the text of a tag inside another tagScrapy:如何在另一个标签内获取标签的文本
【发布时间】:2017-09-24 03:38:48
【问题描述】:

我有这样的 html 段落:

<p>Hello <strong>I'm G </strong></p>

我正在尝试获取 p 中的所有文本。甚至强标签中的部分。 我尝试了下面的代码,但我只得到“你好”。:

for text in response.css("div.entry-content"):
        yield {
            "parag": text.css("p::text").extract(),
        }

我也尝试过类似 css 的 first-child,但这次没有返回:

"parag": text.css("p:strong::text").extract()

编辑:它可以是另一个标签,而不是strong。所以目标是获取第一个子文本

【问题讨论】:

  • css 标签在这里没有用;)

标签: python html css scrapy


【解决方案1】:

这是一个工作示例:

>>> from scrapy.http import HtmlResponse
>>> response = HtmlResponse(url="Test HTML String", body="<p>Hello <strong>I'm G </strong> <b>I write code</b></p>")

# First child
>>> ' '.join(t.strip() for i, t in enumerate(response.css('p ::text').extract()) if i< 2).strip()
u"Hello I'm G"

# All child
>>> ' '.join(t.strip() for t in response.css('p ::text').extract()).strip()
u"Hello I'm G  I write code"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    相关资源
    最近更新 更多