Skip to main content
 首页 » 编程设计

python之如何在 Python 中获取两个 html 标签之间的所有内容

2024年10月25日9kenshinobiy

我尝试从 html 页面上的一个主标记中提取所有内容(标记和文本)。例如:

`my_html_page = ''' 
<html> 
    <body> 
       <div class="post_body"> 
          <span class="polor"> 
             <a class="p-color">Some text</a> 
             <a class="p-color">another text</a> 
          </span> 
          <a class="p-color">hello world</a> 
          <p id="bold"> 
              some text inside p 
             <ul> 
                <li class="list">one li</li> 
                <li>second li</li> 
             </ul> 
         </p> 
         some text 2 
         <div> 
             text inside div 
         </div> 
         some text 3 
      </div> 
      <div class="post_body"> 
          <a>text inside second main div</a> 
      </div> 
      <div class="post_body"> 
          <span>third div</span> 
      </div> 
      <div class="post_body"> 
          <p>four div</p> 
      </div> 
      <div class="post"> 
          other text 
      </div> 
  </body> 
<html>'''` 

我需要开始使用 xpath( "(//div[@class="post_body"])[1]" ):

` 
       <div class="post_body"> 
          <span class="polor"> 
             <a class="p-color">Some text</a> 
             <a class="p-color">another text</a> 
          </span> 
          <a class="p-color">hello world</a> 
          <p id="bold"> 
              some text inside p 
             <ul> 
                <li class="list">one li</li> 
                <li>second li</li> 
             </ul> 
         </p> 
         some text 2 
         <div> 
             text inside div 
         </div> 
         some text 3 
      </div> 
` 

所有内标签<div class="post_body">

我读了this topic , 但它没有帮助。

我需要通过 lxml 中的 beautifulsoup 解析器创建 DOM。

 import lxml.html.soupparser 
 import lxml.html 
 text_inside_tag = lxml.html.soupparser.fromstring(my_html_page) 
 text = text_inside_tag.xpath('(//div[@class="post_body"])[1]/text()') 

而且我只能提取标签内的文本,但我需要提取带有标签的文本。

如果我尝试使用这个:

for elem in text.xpath("(//div[@class="post_body"])[1]/text()"): 
   print lxml.html.tostring(elem, pretty_print=True) 

我有错误:TypeError: Type '_ElementStringResult' cannot be serialized.

请帮忙。

请您参考如下方法:

你可以这样试试:

import lxml.html.soupparser 
import lxml.html 
 
my_html_page = '''...some html markup here...''' 
root = lxml.html.soupparser.fromstring(my_html_page) 
 
for elem in root.xpath("//div[@class='post_body']"): 
    result = elem.text + ''.join(lxml.html.tostring(e, pretty_print=True) for e in elem) 
    print result 

result通过组合父节点中的文本节点构建的变量 <div>带有所有子节点的标记。