Skip to main content
 首页 » 编程设计

python之使用 lxml、python、.tail 的 HTML 解析被 br> 标签分解

2024年10月24日7zengkefu

我有一个网站,我正在尝试抓取(虽然​​不是真正理解 html),但我已经阅读了大量内容并取得了一些进展。这是一个困惑的网站,但重要的部分如下所示:

<h1> 
    <b>DESCRIPTOR1: </b>  
       " important content " 
    <br> 
    <b>DESCRIPTOr2: </b>  
       " important content" 
    <hr> 
</h1> 
 
<b>Title1</b> 
    " A lot of important text" 
<br> 
<br> 
<b>Title2</b> 
    "A lot of important text" 
<br> 
<br> 
<b>Title3</b> 
<br> 
    "1. List of text pertaining to Title3 " 
<br> 
    "2. List of items for Title 3" 
<br>  
    "3. the number of listed items is variable for every page" 
<br> 
    "4. Sometimes no list at all" 
<br> 
<br> 
<b> Next Title: </b> 
 
....and so on 

现在我可以非常接近我想要的最终结果,除了当我到达标题 3 并且有一个 <br> 时。在标题 3 的内容之前。这就是我处理它的方式:

import lxml.html 
 
htmltree = lxml.html.parse('sample.html') 
 
items = htmltree.xpath('//*[@id="sampletext"]/b') 
 
for node in items: 
 
    print (node.text.strip()) 
    print node.tail 

现在我的 2 个问题是 (1):我无法从 .tail's 中删除空格和 (2):我得到 Title3 返回的“无”,因为没有 .tail在下一个元素之前 <br> .理想情况下,我可以添加任何不在元素标签之间的文本,直到我到达我的下一个标识符标签,在本例中是 <b>。 .希望这是有道理的。有什么指点吗?

请您参考如下方法:

您可以尝试使用以下 XPath 表达式:

for item in items: 
    result = item.xpath('following-sibling::text()[normalize-space()][preceding-sibling::b[1] = $b]', b=item) 
    print [r.strip() for r in result] 

针对相关 HTML 片段进行测试时的输出:

['" A lot of important text"'] 
['"A lot of important text"'] 
['"1. List of text pertaining to Title3 "', '"2. List of items for Title 3"', '"3. the number of listed items is variable for every page"', '"4. Sometimes no list at all"'] 
[] 

关于XPath的简要说明:

  • following-sibling::text()[normalize-space()]:查找非空的 following-sibling 文本节点...
  • [preceding-sibling::b[1] = $b] :...其中最近的 preceding-sibling b 元素等于 $b。 $b 是一个 XPath 参数,在上面的代码中用当前的 item 代替。这由 xpath() 方法的第二个参数 (b=item)
  • 指示