我是python自动化的新手。所以我想做的是,我试图在wego.cn上自动进行航班预订,但是当我在xpath中搜索相同内容时,即使我认为我得到了正确的xpath,xpath也不会突出显示。 >
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")
我收到“找不到元素”错误
答案 0 :(得分:0)
该元素位于几个嵌套的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)