You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome中Selenium仅打开开发者工具时可定位元素问题求解

问题描述

当前脚本的功能目标是定位数字图书馆的搜索栏,输入待查找的资源名称,点击对应结果后获取当前页面URL。第一部分向搜索栏输入内容的功能运行正常,但第二个try/finally代码块仅当右键点击页面任意元素选择检查时才会执行,否则会抛出如下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id=\"ember767\"]"}
相关代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains


PATH = "/Applications/chromedriver"
ser = Service(PATH)
driver = webdriver.Chrome(service=ser)
driver.maximize_window()
driver.implicitly_wait(20)

driver.get("https://browzine.com/libraries/1374/subjects")
print("Enter targeted Journal name:")
targeted_journal = input()
wait = WebDriverWait(driver, 10)


try:
    button = driver.find_element(By.ID, "ember648")
    driver.implicitly_wait(10)
    ActionChains(driver).move_to_element(button).click(button).perform()
    button.send_keys(targeted_journal)
    button.send_keys(Keys.RETURN)
finally:
    pass

# 步骤2:点击目标期刊并获取当前URL
try:
    driver.implicitly_wait(20)
    click_journal = driver.find_element(By.ID, "ember767") 
    ActionChains(driver).move_to_element(click_journal).click(click_journal).perform()
    targeted_url = driver.current_url
finally:
    pass

print(targeted_url)
driver.quit()
问题原因说明

更新:已找到问题原因
最初采集的目标元素ID为动态ID,仅在开发者工具窗口打开时才会分配该ID,因此脚本只有在点击「检查元素」时才能检测到该特定ID(本案例中为ember767),其余场景下目标元素不会被分配该ID。要规避该问题,可改用Xpath定位元素。

内容的提问来源于stack exchange,提问作者crackingd0lmen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:06:04