亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

富國滬深 2022-12-06 15:07:17
我試圖獲取 Google Trends 中一個元素的 xpath,該元素似乎是動態的,導致控制臺中出現奇怪的重新加載,這不允許我獲取路徑。因此,我也嘗試通過我看到的 id 進行選擇,但仍然無法正常工作。我想做的是在搜索框中添加一個標題為“添加搜索詞”的比較查詢(在第一次單擊同一元素后)。這是一個示例網址:https ://trends.google.com/trends/explore?q=python%20programming&geo=US也許我需要等待?當我嘗試在控制臺中檢查時,我對隱藏的 html 感到困惑。# click to add and compare querydriver.find_element_by_xpath('//*[@id="explorepage-content-header"]/explore-pills/div/button/span/span[1]').click()time.sleep(10)# find comparisson search boxdriver.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 boxele.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)
查看完整描述

2 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

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


我使用了以下代碼并能夠使其正常工作,但我假設我們總是要進入第二個搜索框。第一個搜索框是原始術語。


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)


查看完整回答
反對 回復 2022-12-06
?
慕雪6442864

TA貢獻1812條經驗 獲得超5個贊

具有動態 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


查看完整回答
反對 回復 2022-12-06
  • 2 回答
  • 0 關注
  • 272 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號