为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 271 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号