我正在嘗試從此
這是我嘗試過的:
#Get First Date (Date at top of the page)
try:
first_date = driver.find_elements_by_css_selector('a[href^="https://www.bandsintown.com/a/"] div div')
first_date = first_date[0].text
except (ElementNotVisibleException, NoSuchElementException, TimeoutException):
print ("first_date doesn't exist")
continue
#Get time. This will the first sibling of the second instance of date
try:
event_time = driver.find_elements_by_xpath("//div[text()='" first_date "'][1]/following-sibling::div")
print(event_time[0].text)
except (ElementNotVisibleException, NoSuchElementException, TimeoutException):
continue
但是,這并沒有讓我得到我想要的。我在這里做錯了什么?我正在尋找一種使用 Xpath 獲取第二個實體的第一個兄弟姐妹的方法。
uj5u.com熱心網友回復:
似乎它是第一個元素PM/AM所以我會使用find_elementwith
'//div[contains(text(), " PM") or contains(text(), " AM")]'
像這樣
item = driver.find_element(By.XPATH, '//div[contains(text(), " PM") or contains(text(), " AM")]')
print(item.text)
PM我在/之前使用空格AM來確保它不在單詞內。
當我添加時,您的 xpath 有效,( )因此它首先獲取 div,然后按索引選擇。
沒有它可能會像()對待。
它需要,而不是因為 xpath 開始計數,而不是[text()="..."][1][text()="..." and 1][2][1]10
"(//div[text()='" first_date "'])[2]/following-sibling::div"
完整的作業示例
from selenium import webdriver
from selenium.webdriver.common.by import By
#from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
import time
url = 'https://www.bandsintown.com/e/103275458-nayo-jones-at-promise-of-justice-initiative?came_from=253&utm_medium=web&utm_source=city_page&utm_campaign=event'
#driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get(url)
time.sleep(5)
item = driver.find_element(By.XPATH, '//div[contains(text(), " PM") or contains(text(), " AM")]')
print(item.text)
print('---')
first_date = driver.find_elements(By.CSS_SELECTOR, 'a[href^="https://www.bandsintown.com/a/"] div div')
first_date = first_date[0].text
event_time = driver.find_elements(By.XPATH, "(//div[text()='" first_date "'])[2]/following-sibling::div")
print(event_time[0].text)
uj5u.com熱心網友回復:
以下 xpath 將為您提供日期和時間。
日期:
print(driver.find_element_by_xpath("//a[text()='Promise of Justice Initiative']/following::div[4]").text)
時間:
print(driver.find_element_by_xpath("//a[text()='Promise of Justice Initiative']/following::div[5]").text)
或您的使用。
print(driver.find_element_by_xpath("
//a[contains(@href,'https://www.bandsintown.com/v/')]/following::div[contains(text(), 'PM') or contains(text(), 'AM')]").text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/449117.html
上一篇:SessionNotCreatedException:訊息:會話未創建:此版本的ChromeDriver僅支持Chrome版本99
