我正在尝试浏览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()
因此,如您所见,代码将转到PADI,找到每艘潜水船的所有卡片,并将其发还给我。这里使用的xpath来自可用的最近ID,但是从那一点开始,它是所有绝对路径div / div / div等。我想知道是否可以将其更改为相对路径。
谢谢。
您应该使用class
和/或id
使其更短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('---')
结果示例(您可以使用其他货币表示价格)
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
---
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句