簡體   English   中英

Selenium - 無法在動態元素中獲取 xpath

[英]Selenium - Not able to get xpath in dynamic element

我試圖在 Google 趨勢中獲取一個元素的 xpath,該元素似乎是動態的,導致控制台中出現奇怪的重新加載,這不允許我獲取路徑。 因此,我還嘗試通過我看到的 id 進行選擇,但仍然無法正常工作。

我想做的是在搜索框中添加一個標題為“添加搜索詞”的比較查詢(在第一次單擊同一元素之后)。

下面是一個示例 url: https://trends.google.com/trends/explore?q=python%20programming&geo=US

是不是我需要等待? 當我嘗試在控制台中檢查時,我對隱藏的 html 感到困惑。

# click to add and compare query
driver.find_element_by_xpath('//*[@id="explorepage-content-header"]/explore-pills/div/button/span/span[1]').click()
time.sleep(10)

# find comparisson search box
driver.maximize_window() 
driver.implicitly_wait(20) 
ele = driver.find_element_by_id('input-139')
time.sleep(1)

ele.send_keys('r programming') <-- im not able to add this query in the comparison box
ele.send_keys(Keys.RETURN)

這是錯誤信息。

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="input-139"]"}
  (Session info: chrome=81.0.4044.138)

該頁面似乎在頁面重新加載期間和在不同的瀏覽器上生成不同的 ID。 我假設這很可能與頁面使用 angular 的事實有關。

我使用了下面的代碼並且能夠讓它工作,但我認為我們總是要進入第二個搜索框。 第一個搜索框是原始術語。

search_boxes = driver.find_elements_by_css_selector('input[aria-label="Add a search term"]')
target_box = search_boxes[1] # Second Box, we're assuming there is always one term.

target_box.send_keys('r programming')
target_box.send_keys(Keys.RETURN)

具有動態 id 的輸入字段,您不能使用.find_element_by_id('input-139') 並嘗試像下面這樣添加WebDriverWait

driver.get('https://trends.google.com/trends/explore?q=python%20programming&geo=US')
compare = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CLASS_NAME, 'add-term-text')))
compare.click()
input_elmnt = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#explorepage-content-header > explore-pills > div > div:nth-child(2)')))
action = ActionChains(driver)
action.move_to_element(input_elmnt).send_keys('r programming').send_keys(Keys.ENTER).perform()

導入后:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys

暫無
暫無

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

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