簡體   English   中英

如何定位在 shadow-root 中找不到的元素

[英]How to locate element not found in shadow-root

我是 python 自動化的新手。 所以我想做的是我試圖在 wego.co.in 上自動進行航班預訂,但是當我搜索 xpath 時,xpath 並沒有突出顯示,即使我認為我得到了正確的 Z3D788FA62D7C1805A1ZEE4。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep

driver = webdriver.Chrome()
driver.maximize_window()

driver.get("https://www.wego.co.in/")

fly_from = driver.find_element_by_xpath('//input[@placeholder="From"]').click()
fly_from.send_keys("New Delhi, India")
sleep(0.1)
fly_to = driver.find_element_by_xpath('//input[@placeholder="to"]').click()
fly_to.send_keys("Goa, India")

我收到“找不到元素”錯誤

該元素位於幾個嵌套shadow-root部分中。 您需要像<ifram>一樣一次切換到每個部分,但是 Selenium 沒有對shadow-root的內置支持。

一種解決方法是使用 JavaScript 將shadow-root部分作為 WebElement 獲取,並使用此元素定位該部分內的元素

driver.get("https://www.wego.co.in/")

element = driver.find_element_by_id('app')
shadow_root = self.get_shadow_root(driver, element)

element = shadow_root.find_element_by_css_selector('[id="base"] > wego-search-form')
shadow_root = self.get_shadow_root(driver, element)

element = shadow_root.find_element_by_class_name('flightSearchForm')
search_bar_shadow_root = self.get_shadow_root(driver, element)

element = search_bar_shadow_root.find_element_by_id('dep')
shadow_root = self.get_shadow_root(driver, element)

fly_from = shadow_root.find_element_by_css_selector('[placeholder="From"]')
fly_from.click()
fly_from.send_keys("New Delhi, India")

element = search_bar_shadow_root.find_element_by_id('arr')
shadow_root = self.get_shadow_root(driver, element)

fly_to = shadow_root.find_element_by_css_selector('[placeholder="to"]')
fly_to.click()
fly_to.send_keys("Goa, India")

def get_shadow_root(self, driver, element):
    return driver.execute_script('return arguments[0].shadowRoot', element)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM