鍍金池/ 問答/Python  網(wǎng)絡(luò)安全/ Xpath如何提取html標(biāo)簽(HTML標(biāo)簽和內(nèi)容)

Xpath如何提取html標(biāo)簽(HTML標(biāo)簽和內(nèi)容)

<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標(biāo)簽提取出來,結(jié)果如下:

<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對象轉(zhuǎn)成str類型
回答
編輯回答
尐潴豬

BeautifulSoup的find

2017年11月23日 18:33
編輯回答
氕氘氚

[div/table]就行吧貌似

2018年2月13日 23:32
編輯回答
久舊酒
from lxml import etree
div = etree.HTML(html)
table = div.xpath('//div/table')[0]
content = etree.tostring(table,print_pretty=True, method='html')  # 轉(zhuǎn)為字符串
2017年3月13日 17:40
編輯回答
老梗
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標(biāo)簽
original_html = tostring(content)
2017年5月19日 02:29