python中的selenium通过相对xpath查找元素

D.Z*_*Zou 5 python selenium xpath

我正在尝试浏览 PADI 船宿页面以获取一些船只、出发日期和价格信息。我能够从 chrome 调试控制台获取 xpath 并让 selenium 找到它。但我想通过使用相对路径让它变得更好,但我不知道该怎么做。这是我到目前为止得到的:

from selenium import webdriver
import pdb

browser = webdriver.Chrome()


browser.get('https://travel.padi.com/s/liveaboards/caribbean/')
assert 'Caribbean' in browser.title


elem2 = browser.find_elements_by_xpath('//*[@id="search-la"]/div/div[3]/div/div[2]/div[3]/div')

print(elem2)
print(len(elem2))

browser.close()

Run Code Online (Sandbox Code Playgroud)

正如您所看到的,代码将发送至 PADI,找到每艘潜水船的所有卡片,并将其以列表的形式返还给我。这里使用的 xpath 来自最近的可用 id,但从那时起,它都是绝对路径 div/div/div 等。我想知道是否可以以某种方式将其更改为相对路径。

谢谢。

fur*_*ras 7

您应该使用classand/orid来缩短xpath.

当您找到cards时,您可以使用以-xpath开头的每张卡./,因此它将xpath相对于该元素,并且只会在该元素内搜索。

您还可以//在 的任何部分使用xpath来跳过一些不重要的标签。

您可以使用 otherfind_element_by_find_elements_by_with card,它也只会在该元素内部搜索 - 所以它将是相对的。

import selenium.webdriver

driver = selenium.webdriver.Chrome() # Firefox()

driver.get('https://travel.padi.com/s/liveaboards/caribbean/')

all_cards = driver.find_elements_by_xpath('//div[@class="boat search-page-item-card "]')

for card in all_cards:
    title = card.find_element_by_xpath('.//a[@class="shop-title"]/span')
    desc  = card.find_element_by_xpath('.//p[@class="shop-desc-text"]')
    price = card.find_element_by_xpath('.//p[@class="cur-price"]/strong/span')

    print('title:', title.text)
    print('desc:',  desc.text)
    print('price:', price.text)

    all_dates = card.find_elements_by_css_selector('.cell.date')

    for date in all_dates:
        day, month = date.find_elements_by_tag_name('span')
        print('date:', day.text, month.text)

    print('---')
Run Code Online (Sandbox Code Playgroud)

结果示例(您可以有不同货币的价格)

title: CARIBBEAN EXPLORER II
desc: With incredible, off-the-beaten path itineraries that take guests to St Kitts, Saba and St Maarten, this leading liveaboard spoils divers with five dives each day, scenic geography and a unique slice of Caribbean culture.
Dates do not match your search criteria
price: PLN 824
date: 7 DEC
date: 14 DEC
date: 21 DEC
date: 28 DEC
---
title: BAHAMAS AGGRESSOR
desc: Featuring five dives a day, the well-regarded Bahamas Aggressor liveaboard is the ideal choice for divers who want to spend as much time under the water as possible then relax in an onboard Jacuzzi.
Dates do not match your search criteria
price: PLN 998
date: 7 DEC
date: 14 DEC
date: 21 DEC
date: 28 DEC
---
Run Code Online (Sandbox Code Playgroud)