【问题标题】:How to use xpath to extract text in more than one label of html scripts如何使用xpath提取多个html脚本标签中的文本
【发布时间】:2015-01-17 06:28:17
【问题描述】:

假设我有很多这样的 html 脚本:

<div style="clear:both" id="novelintro" itemprop="description">you are foolish!<font color=red size=4>I am superman!</font></div>

我想用xpath来提取文字:你太傻了!我是超人!

但是,如果我使用

xpath('//div[@id="novelintro"]/text()').extract()

我只能得到“你太傻了!”

当我使用时:

xpath('//div[@id="novelintro"]/font/text()').extract()"

我只能得到“我是超人!”

所以如果你只能使用一个 xpath 表达式来提取整个句子“你是愚蠢的!我是超人!”

而且比较倒霉,在上面的html脚本中,是“<font>”标签,但是在我的其他脚本中,还有很多其他标签,例如:

提取“嗨,女孩,我爱你!”在以下脚本中: <div style="clear:both" id="novelintro" itemprop="description">hi girl<legend >I love you!</legend></div>

提取“如果我嫁给你的母亲,那么我就是你的父亲!”在以下脚本中:

<div style="clear:both" id="novelintro" itemprop="description">If I<legend > marry your mother<div>then I am your father!</div></legend></div>

如果你可以只使用一个 xpath 表达式来适配所有的 html 脚本?

【问题讨论】:

    标签: python html xml xpath scrapy


    【解决方案1】:

    您可以使用 XPath 的string() 函数,它递归地将单个节点转换为字符串(可选的. 指的是当前节点):

    from scrapy.selector import HtmlXPathSelector
    
    def node_to_string(node):
        return node.xpath("string(.)").extract()[0]
    
    # ------------------------------------------------------
    
    body = """<body>
      <div style="clear:both" id="novelintro" itemprop="description">you are foolish!<font color=red size=4>I am superman!</font></div>
      <div style="clear:both" id="novelintro2" itemprop="description">hi girl<legend >I love you!</legend></div>
      <div style="clear:both" id="novelintro3" itemprop="description">If I<legend > marry your mother<div>then I am your father!</div></legend></div>
    </body>"""
    
    hxs = HtmlXPathSelector(text=body)
    
    # single target use
    print node_to_string(hxs.xpath('//div[@id="novelintro"]'))
    print 
    
    # multi target use
    for div in hxs.xpath('//body/div'):
        print node_to_string(div)
    print 
    
    # alternatively
    print [node_to_string(n) for n in hxs.xpath('//body/div')]
    print 
    

    输出

    你太傻了!我是超人! 你太傻了!我是超人! 嗨女孩我爱你! 如果我嫁给你妈妈,那我就是你爸爸! [你是愚蠢的!我是超人!',你好女孩我爱你!',你'如果我嫁给你的母亲,那么我就是你的父亲!']

    请注意,由于源中缺少空格,因此缺少空格。 string() 处理空格的方式与浏览器相同。

    【讨论】:

    • 这就是我需要的!!!!非常感谢!!!我可以在我的博客中写出这个绝妙的方法吗?
    • 当然,如果你清楚地引用了这篇文章(StackOverflow 上的所有内容都是 CC-BY-SA)。
    【解决方案2】:

    如果您的文档是:

    <outer>This is outer text.<inner>And this is inner text.</inner>More outer text.</outer>
    

    你使用 xpath 表达式:/outer//text() (阅读:“外部”下方的任何文本),结果是一个看起来像这样的列表:

    This is outer text. ----------------------- And this is inner text. ----------------------- More outer text.

    【讨论】:

    • 谢谢,很有用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2013-03-16
    • 2017-02-24
    • 2017-09-07
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    相关资源
    最近更新 更多