在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網絡安全/ Xpath如何提取html標簽(HTML標簽和內容)

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類型
回答
編輯回答
尐潴豬

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')  # 轉為字符串
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標簽
original_html = tostring(content)
2017年5月19日 02:29