天天看點

Python爬蟲利器Xpath文法與lxml庫的用法

選取節點

XPath 使用路徑表達式在 XML 文檔中選取節點。節點是通過沿着路徑或者 step 來選取的。

下面列出了最有用的路徑表達式:

表達式 描述
nodename 選取此節點的所有子節點。
/ 從根節點選取。
// 從比對選擇的目前節點選擇文檔中的節點,而不考慮它們的位置。
. 選取目前節點。
.. 選取目前節點的父節點。
@ 選取屬性。

執行個體

在下面的表格中,我們已列出了一些路徑表達式以及表達式的結果:

路徑表達式 結果
bookstore 選取 bookstore 元素的所有子節點。
/bookstore 選取根元素 bookstore。注釋:假如路徑起始于正斜杠( / ),則此路徑始終代表到某元素的絕對路徑!
bookstore/book 選取屬于 bookstore 的子元素的所有 book 元素。
//book 選取所有 book 子元素,而不管它們在文檔中的位置。
bookstore//book 選擇屬于 bookstore 元素的後代的所有 book 元素,而不管它們位于 bookstore 之下的什麼位置。
//@lang 選取名為 lang 的所有屬性。

謂語(Predicates)

謂語用來查找某個特定的節點或者包含某個指定的值的節點。

謂語被嵌在方括号中。

執行個體

在下面的表格中,我們列出了帶有謂語的一些路徑表達式,以及表達式的結果:

路徑表達式 結果
/bookstore/book[1] 選取屬于 bookstore 子元素的第一個 book 元素。
/bookstore/book[last()] 選取屬于 bookstore 子元素的最後一個 book 元素。
/bookstore/book[last()-1] 選取屬于 bookstore 子元素的倒數第二個 book 元素。
/bookstore/book[position()<3] 選取最前面的兩個屬于 bookstore 元素的子元素的 book 元素。
//title[@lang] 選取所有擁有名為 lang 的屬性的 title 元素。
//title[@lang=’eng’] 選取所有 title 元素,且這些元素擁有值為 eng 的 lang 屬性。
/bookstore/book[price>35.00] 選取 bookstore 元素的所有 book 元素,且其中的 price 元素的值須大于 35.00。
/bookstore/book[price>35.00]/title 選取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值須大于 35.00。

選取未知節點

XPath 通配符可用來選取未知的 XML 元素。

通配符 描述
* 比對任何元素節點。
@* 比對任何屬性節點。
node() 比對任何類型的節點。

執行個體

在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:

路徑表達式 結果
/bookstore/* 選取 bookstore 元素的所有子元素。
//* 選取文檔中的所有元素。
//title[@*] 選取所有帶有屬性的 title 元素。

選取若幹路徑

通過在路徑表達式中使用“|”運算符,您可以選取若幹個路徑。

執行個體

在下面的表格中,我們列出了一些路徑表達式,以及這些表達式的結果:

路徑表達式 結果
//book/title | //book/price 選取 book 元素的所有 title 和 price 元素。
//title | //price 選取文檔中的所有 title 和 price 元素。
/bookstore/book/title | //price 選取屬于 bookstore 元素的 book 元素的所有 title 元素,以及文檔中所有的 price 元素。

XPath 運算符

下面列出了可用在 XPath 表達式中的運算符:

運算符 描述 執行個體 傳回值
| 計算兩個節點集 //book | //cd 傳回所有擁有 book 和 cd 元素的節點集
+ 加法 6 + 4 10
減法 6 – 4 2
* 乘法 6 * 4 24
div 除法 8 div 4 2
= 等于 price=9.80 如果 price 是 9.80,則傳回 true。如果 price 是 9.90,則傳回 false。
!= 不等于 price!=9.80 如果 price 是 9.90,則傳回 true。如果 price 是 9.80,則傳回 false。
< 小于 price<9.80 如果 price 是 9.00,則傳回 true。如果 price 是 9.90,則傳回 false。
<= 小于或等于 price<=9.80 如果 price 是 9.00,則傳回 true。如果 price 是 9.90,則傳回 false。
> 大于 price>9.80 如果 price 是 9.90,則傳回 true。如果 price 是 9.80,則傳回 false。
>= 大于或等于 price>=9.80 如果 price 是 9.90,則傳回 true。如果 price 是 9.70,則傳回 false。
or price=9.80 or price=9.70 如果 price 是 9.80,則傳回 true。如果 price 是 9.50,則傳回 false。
and price>9.00 and price<9.90 如果 price 是 9.80,則傳回 true。如果 price 是 8.50,則傳回 false。
mod 計算除法的餘數 5 mod 2 1

1.安裝:

import requests
from lxml import etree
import json
main_url = 'http://www.hx2car.com/details/162837726?position=011302'
headers = {
    "User-Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 71.0.3578.98Safari / 537.36",
}
res = requests.get(main_url, headers=headers)
res.encoding = 'utf-8'

root = etree.HTML(res.content)
title = []#标題
title_s = root.xpath('//div[@class="top_R"]/h2/text()')
title_e = root.xpath('//div[@class="top_R"]/h2/span/text()')
title.append(title_s[0].strip('\n , \xa0'))
title.append(title_e[0].strip('\n , \xa0'))
prices = root.xpath('//span[@class="cf60 price"]/span/text()')
prices = ''.join(e for e in prices[0].strip('\n , \xa0 \t') if e.strip('\n , \xa0 \t'))#價格
kilometre = root.xpath('//div[@class="car_info"]/ul/li[1]/p[1]/text()')#行駛公裡
discharge = root.xpath('//div[@class="car_info"]/ul/li[2]/p[1]/text()')#排放/排量
purpose = root.xpath('//div[@class="car_info"]/ul/li[last()]/p[1]/text()')#用途
card_time = root.xpath('//div[@class="opt_box"]/div[1]/div[4]/text()')#上牌日期
color = root.xpath('//div[@class="opt_box"]/div[1]/div[5]/text()')#顔色
contacts = root.xpath('//div[@class="intro"]/div[2]/div[1]/a/text()')#聯系人
address = root.xpath('//span[@id="IArea"]/text()')
address = address[0].strip('\n , \xa0')#位址
#擷取汽車圖檔
picture = []
picture_srcs = root.xpath('//div[@id="detail_pic"]/p/img/@src')
for picture_src in picture_srcs:
    picture_name = picture_src.split("/")[-1]
    res = requests.get(picture_src, headers=headers)
    with open('./hx/'+picture_name,'bw') as f:
        f.write(res.content)
    picture.append(picture_name)
"""
進入門店
"""
go = root.xpath('//a[@class="intro_shops"]/@href')
res = requests.get(go[0], headers=headers)
res.encoding = 'utf-8'
root = etree.HTML(res.content)
m_title = root.xpath('//span[@class="title"]/text()')[0]#公司
photo = root.xpath('//span[@class="tel"]/text()')[0].strip('\n , \xa0 \t')#電話
data = {
    'title':title,
    'prices':prices,
    'kilometre':kilometre,
    'discharge':discharge,
    'purpose':purpose,
    'card_time':card_time,
    'color':color,
    'contacts':contacts,
    'address':address,
    'm_title':m_title,
    'photo':photo,
    'picture':picture
}
with open('./hx/data.json', 'w',encoding='utf-8') as f:
    f.write(json.dumps(data,ensure_ascii=False))