| 表達式 | 描述 |
|---|---|
| / | 從根節(jié)點選?。ㄈ∽庸?jié)點) |
| // | 選擇的當前節(jié)點選擇文檔中的節(jié)點 |
| . | 選取當前節(jié)點。 |
| … | 選取當前節(jié)點的父節(jié)點。 |
| @ | 選取屬性 |
| * | 表示任意內容(通配符) |
| | | 運算符可以選取多個路徑 |
常用功能函數(shù)
| 函數(shù) | 用法 | 解釋 |
|---|---|---|
| startswith() | xpath(‘//div[starts-with(@id,”ma”)]‘) | #選取id值以ma開頭的div節(jié)點 |
| contains() | xpath(‘//div[contains(@id,”ma”)]‘) | #選取id值包含ma的div節(jié)點 |
| and() | xpath(‘//div[contains(@id,”ma”) and contains(@id,”in”)]‘) | #選取id值包含ma的div節(jié)點 |
| text() | _.xpath('./div/div[4]/a/em/text()') | #選取em標簽下文本內容 |
備注:
1、html中當相同層次存在多個標簽例如div,它們的順序是從1開始,不是0
2、瀏覽器中使用開發(fā)者工具可以快速獲取節(jié)點信息

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2021/9/7 9:35
# @Author : Sun
# @Email : 8009@163.com
# @File : sun_test.py
# @Software: PyCharm
import requests
from lxml import etree
def get_web_content():
try:
url = "htpps://***keyword=%E6%97%A0%E9%92%A2%E5%9C%88wq=%E6%97%A0%E"
"9%92%A2%E5%9C%88ev=1_68131%5Epvid=afbf41410b164c1b91d"
"abdf18ae8ab5cpage=5s=116click=0 "
header = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64)"
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/75.0.3770.100 Safari/537.36 "}
response = requests.request(method="Get", url=url, headers=header)
result = response.text
return result
except TimeoutError as e:
return None
def parsing():
result = get_web_content()
if result is not None:
html = etree.HTML(result)
# 先獲取一個大的節(jié)點,包含了想要獲取的所有信息
ii = html.xpath('//*[@id="J_goodsList"]/ul/li')
for _ in ii:
# 采用循環(huán),依次從大節(jié)點中獲取小的節(jié)點內容
# ''.join() 將列表中的內容拼接成一個字符串
infoResult = {
# @href 表示:獲取屬性為href的內容
'href': "https:" + _.xpath('./div/div[1]/a/@href')[0],
'title': ''.join(
_.xpath('./div/div[2]/div/ul/li/a/@title')),
# text()表示獲取節(jié)點i里面的文本信息
'price': _.xpath('./div/div[3]/strong/i/text()')[0],
'info': ''.join(
_.xpath('./div/div[4]/a/em/text()')).strip(),
'province': _.xpath('./div/div[9]/@data-province')[0]}
print(infoResult)
else:
raise Exception("Failed to get page information, please check!")
return None
if __name__ == '__main__':
parsing()
結果圖片:

到此這篇關于python使用xpath獲取頁面元素的使用的文章就介紹到這了,更多相關python xpath獲取頁面元素內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!