【问题标题】:How do I get the inner html content in this xpath expression?如何在此 xpath 表达式中获取内部 html 内容?
【发布时间】:2017-10-21 07:48:12
【问题描述】:

我有一些 HTML 代码

<li><h3>Number Theory - Even Factors</h3>
    <p lang="title">Number N = 2<sup>6</sup> * 5<sup>5</sup> * 7<sup>6</sup> * 10<sup>7</sup>; how many factors of N are even numbers?</p>
    <ol class="xyz">
        <li>1183</li>
        <li>1200</li>
        <li>1050</li>
        <li>840</li>
    </ol>
    <ul class="exp">
        <li class="grey fleft">
            <span class="qlabs_tooltip_bottom qlabs_tooltip_style_33" style="cursor:pointer;">
            <span>
                <strong>Correct Answer</strong>
                    Choice (A).</br>1183
                </span> 
                Correct answer
            </span>
        </li>
        <li class="primary fleft">
            <a href="factors_6.shtml">Explanatory Answer</a>
        </li>
        <li class="grey1 fleft">Factors - Even numbers</li>
        <li class="orange flrt">Medium</li>
    </ul>       
</li>

在上面的 HTML sn-p 中,我试图提取 &lt;p lang="title"&gt; Notice how it has &lt;sup&gt;&lt;/sup&gt; and &lt;sub&gt;&lt;/sub&gt; tags being used inside.

我的 Xpath 表达式 .//p[@lang="title"]/text() 不检索 sub 和 sup 内容。我如何在下面得到这个输出

期望的输出

Number N = 2<sup>6</sup>*5<sup>5</sup> * 7<sup>6</sup> * 10<sup>7</sup>; how many factors of N are even numbers?

【问题讨论】:

标签: xpath html-parsing


【解决方案1】:

XPath

您可以通过node() 简单地获取innerHTML,如下所示:

//p[@lang="title"]/node()

注意它返回的是一个节点数组

Python

您可以通过以下Python 代码获取所需的innerHTML

from BeautifulSoup import BeautifulSoup

def innerHTML(element):
    "Function that receives element and returns its innerHTML"
    return element.decode_contents(formatter="html")

html = """<html>
               <head>...
               <body>...
               Your HTML source code
               ..."""

soup = BeautifulSoup(html)
paragraph = soup.find('p', { "lang" : "title" })

print(innerHTML(paragraph))

输出:

'Number N = 2<sup>6</sup> * 5<sup>5</sup> * 7<sup>6</sup> * 10<sup>7</sup>; how many factors of N are even numbers?'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2023-04-02
    • 2023-03-12
    相关资源
    最近更新 更多