【问题标题】:Code not working. I am trying to click an element on a page with its id number but i cant代码不起作用。我正在尝试使用其 ID 号单击页面上的元素,但我不能
【发布时间】:2021-09-21 01:22:36
【问题描述】:

我需要使用 HTML 代码中的 ID 单击页面上的元素。此按钮的 ID 是“input-optionXXX”,其中 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:\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)

【问题讨论】:

  • 让你知道什么是 EC => from selenium.webdriver.support import expected_conditions as EC
  • 抱歉,code not working 不是诊断。有什么症状吗?您可以在您确定 3 位数字应该是什么的页面上运行此代码吗?
  • 第 64 行,在 driver.find_element_by_id(f'input-option{i}').click()
  • selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"css selector","selector":"[id="input-option100" ]"}
  • 请使用完整的错误回溯更新您的问题。

标签: python html python-3.x selenium selenium-chromedriver


【解决方案1】:

使用 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

【讨论】:

    【解决方案2】:

    如果您尝试确定存在哪些 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多