Xpath如何提取html标签(HTML标签和内容)

<div>
   <table>
      <tr>
         <td class="td class">Row value 1</td>
         <td class="td class">Row value 2</td>
      </tr>
      <tr>
         <td class="td class">Row value 3</td>
         <td class="second td class">Row value 4</td>
      </tr>
      <tr>
         <td class="third td class">Row value 1</td>
         <td class="td class">Row value 1</td>
      </tr>
   </table>
</div>

如何把table标签提取出来,结果如下:

<table>
  <tr>
     <td class="td class">Row value 1</td>
     <td class="td class">Row value 2</td>
  </tr>
  <tr>
     <td class="td class">Row value 3</td>
     <td class="second td class">Row value 4</td>
  </tr>
  <tr>
     <td class="third td class">Row value 1</td>
     <td class="td class">Row value 1</td>
  </tr>
</table>

代码如下:

selector = etree.HTML(html)
content = selector.xpath('//div/table')[0]
print(content)
# <Element div at 0x1bce7463548>
# 即:如何将Element对象转成str类型
阅读 12.1k
4 个回答
from lxml import etree
div = etree.HTML(html)
table = div.xpath('//div/table')[0]
content = etree.tostring(table,print_pretty=True, method='html')  # 转为字符串

[div/table]就行吧貌似

from lxml.html import fromstring, tostring
# fromstring返回一个HtmlElement对象
# selector = fromstring(html)

selector = etree.HTML(html)
content = selector.xpath('//div/table')[0]
print(content)

# tostring方法即可返回原始html标签
original_html = tostring(content)
新手上路,请多包涵

BeautifulSoup的find

推荐问题
宣传栏