2017-03-02 47 views
0

我試圖從以下結構的HTML文件中的文本:從HTML中提取文本穿插着大膽的標籤,維持秩序

<td class='srctext> 
<pre> 
    <b> Heading 1 </b> 
    text 
    more text 
    <b> Heading 2 </b> 
    even more text, 
    <b> also some bold text </b> 
    and the last text 
</pre> 

要做到這一點我使用XPath的,像

//td[@class='srctext]/pre/b 

這樣做我得到的所有粗體標記的內部文本,我也可以得到預先的整個內部文本,通過使用字符串()包裝。

但是我很努力做的,越來越像一個結果:

[ 
    'Heading 1', 
    'text \n more text', 
    'Heading 2', 
    'even more text', 
    ... 
] 

請不要猶豫,問,如果有不清楚的地方。

回答

0

嘗試//td[@class='srctext']/pre//text()[normalize-space()]作爲XPath(假設您有完整的XPath 1.0支持,例如lxml和不受限制的ElementTree XPath支持)。

完整的例子就是

from lxml import etree as ET 
html = '''<html><body><table><tr><td class=srctext> 
<pre> 
    <b> Heading 1 </b> 
    text 
    more text 
    <b> Heading 2 </b> 
    even more text, 
    <b> also some bold text </b> 
    and the last text 
</pre> 
</body> 
</html>''' 

htmlEl = ET.HTML(html) 
textValues = htmlEl.xpath("//td[@class='srctext']/pre//text()[normalize-space()]") 
print(textValues) 

和輸出

[' Heading 1 ', '\n text\n more text\n ', ' Heading 2 ', '\n even more text, \n ', ' also some bold text ', '\n and the last text\n'] 
0

如果我正確理解你的問題,你要忽略HTML struture並在列表中提取文本的碎片,每個列表元素是一個不包含任何標籤的字符串。

通常使用正則表達式來解析XML或HTML是一個可怕的想法,但這個問題是它的一個罕見用例。假定您已經閱讀所有的文件在一個單一的字符串:

[ i.strip() for i in re.findall(r'(.*?)<.*?>', t, re.DOTALL) if len(i.strip()) > 0] 

給出預期:

['Heading 1', 'text\n more text', 'Heading 2', 'even more text,', 'also some bold text', 'and the last text']