[英]Code not working. I am trying to click an element on a page with its id number but i cant
I need to click an element on a page by using its ID from the HTML code.我需要使用 HTML 代码中的 ID 单击页面上的元素。 The ID of this button is "input-optionXXX" where XXX is a 3 digit number between 100 and 400. I want the python code to run through the HTML code on the page and find out what the 3 digit number (between 100 and 400) is so it can click on it.
这个按钮的ID是“input-optionXXX”,其中XXX是100到400之间的3位数字。我想让python代码运行页面上的HTML代码,找出3位数字(100到400之间)是什么) 这样它就可以点击它了。 Any help?
有什么帮助吗?
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:\Users\karim\Desktop\b1.py", line 64, in <module>
driver.find_element_by_id(f'input-option{i}').click()
File "C:\Users\karim\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:\Users\karim\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "C:\Users\karim\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\karim\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.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)
Use try...except block:使用 try...except 块:
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
If you are trying to determine which ids are present, then:如果您要确定存在哪些 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.