1. 程式人生 > >python進階(lxml的用法)

python進階(lxml的用法)

                   本節處理的檔案如下,檔名為:webhtml.html

<!DOCTYPE html>
<html>
<head>
	<title>漏斗圖</title>
	<script type="text/javascript" src="./echarts.js"></script>
</head>
<body>
	<div id="main" style="width: 800px;height: 600px">1111</div>
	<article id="main2" style="width: 800px;height: 600px">
		<span>
			logo
			<a href="http://www.baidu.com" style="font-size:15px;">taobao</a>
			<b>hahaha<em>3333</em></b>
			<a href="www.baidu.com">taobao2</a>
		</span>
	</article>
	<div id="last">last... ...</div>
	<div class="one">11111111111111111111111</div>
	<div class="one two" name="sec" data-foo="value">22222222222222222222222</div>
	<div id="left">
		<a href="http://www.taobao1.com">11111</a>
		<a href="http://www.taobao2.com">333333</a>
		<a href="http://www.taobao3.com">4444</a>
		<a href="http://www.taobao4.com">55555</a>
	</div>
	<script type="text/javascript">
		var myChart=echarts.init(document.getElementById('main'))
		var option={
			title:{
				text:"你的附近哪家自助貨架比較多",
				subtext:"資料地區:上海",
			},
			tooltip:{
				// trigger:'item'   //not axis
			},
			legend:{
				orient:"vertical",
				left:"left",
				top:"center",
				data:['猩便利','小u貨架','友寶','峰小櫃','小e微店']
				//data中的名字和series 中data中的name相等
			},
			toolbox:{
				// show:true,
				feature:{              //feature  不是 true
					// mark:{
					// 	show:true
					// },
					dataView:{
						show:true,
						readOnly:true
					},
					restore:{
						show:true
					},
					saveAsImage:{
						show:true
					}
				}
			},
			series:[{
				name:"貨架詳情",
				type:"funnel",
				left:"30%",
				max:100,
				min:0,
				data:[
					{
						value:100,
						name:"猩便利",
					},{
						value:80,
						name:"友寶"
					},{
						value:60,
						name:"峰小櫃"
					},{
						name:"小u貨架",
						value:20
					},{
						name:"小e微店",
						value:40
					}
				]
			}]
		}
		myChart.setOption(option)
 
	</script>
</body>
</html>

一、lxml的基本知識:

           ①xpath路徑可以放在瀏覽器中檢視。

           ②string得到結果是str,/text()得到的結果是list

           ③  /@屬性名  得到的結果也是list

1、lxml物件的建立:

(1)通過resquests響應內容:

from lxml import etree
import requests
                              響應內容
responce1 = requests.get('https://www.baidu.com').content.decode('utf-8')
html_lxml = etree.HTML(responce1)    建立lxml物件          

(2)開啟本地檔案: 

2、將lxml物件序列化:

result = etree.tostring(html_lxml,pretty_print=True,encoding='utf-8').decode('utf-8')
print(result)

二、xpath語法:

1、選取節點:

2、謂語:

3、xpath萬用字元:

4、例項:

5、xpath運算子:

                      其中 或(|)比較常用。

 < >= 等運算子用於標籤內容比較,如例:

 6、xpath獲得標籤屬性和標籤內容:

                獲得是內容,而不是標籤本身。

  • ① /text() 獲取第一層節點的所有內容,不包括子節點,且結果是list。
  • ② /@屬性名: 獲得標籤的屬性,結果也是 list。
  • ③ string 獲得所有節點的內容,包括子節點,結果是 str 。

7、例項: