代码不起作用.我正试图用id号点击页面上的一个元素,但我不能



我需要使用HTML代码中的元素ID来单击页面上的元素。这个按钮的ID是";输入选项XXX";其中XXX是介于100和400之间的3位数字。我想让python代码在页面上的HTML代码中运行,找出3位数(在100到400之间(是什么,这样它就可以点击它了。有什么帮助吗?

a = list(range(100,400))
for i in a:
if EC.presence_of_element_located((By.ID, f'input-option{str(i)}')):
driver.find_element_by_id(f'input-option{i}').click()
print(i)
Traceback (most recent call last):
File "C:UserskarimDesktopb1.py", line 64, in <module>
driver.find_element_by_id(f'input-option{i}').click()
File "C:UserskarimAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremotewebdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:UserskarimAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremotewebdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:UserskarimAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremotewebdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:UserskarimAppDataLocalProgramsPythonPython39libsite-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="input-option100"]"}
(Session info: chrome=xxxxxxxxxxxx)

使用try。。。除块:

from selenium.common.exceptions import NoSuchElementException
for i in range(100, 400):
try:
driver.find_element_by_id(f'input-option{i}').click()
print(i)
except NoSuchElementException:
continue

如果您试图确定存在哪些id,则:

for i in range(100, 400):
# The following might return an empty list but should not throw an exception:
elements = driver.find_elements_by_id(f'input-option{i}')
if elements:
elements[0].click()
print(i)

相关内容

  • 没有找到相关文章

最新更新