【问题标题】:How to get element by tag name or id in python selenium [duplicate]如何在python selenium中通过标签名称或id获取元素[重复]
【发布时间】:2022-11-11 03:05:02
【问题描述】:

我正在尝试使用 Python 和 Selenium 获取输入,但它向我显示了一个错误。我该如何解决这个错误?

inputElement.send_keys(getStock.getStocklFunc()[0])

错误

inputElement = driver.find_element(by=By.CLASS_NAME, value='su-input-group')
NameError: name 'By' is not defined. Did you mean: 'py'?

我也试过这条线,但它显示一个弃用错误

find_element_by_tag_name

【问题讨论】:

    标签: python selenium selenium-webdriver tagname


    【解决方案1】:

    当您想按类名定位元素时使用此选项。使用此策略,将返回具有匹配类名称属性的第一个元素。如果没有元素具有匹配的类名属性,则会引发 NoSuchElementException。

    例如,考虑这个页面源:

    <html>
     <body>
      <p class="content">Site content goes here.</p>
    </body>
    </html>
    

    “p”元素可以这样定位:

    content = driver.find_element_by_class_name('content')
    

    https://selenium-python.readthedocs.io/locating-elements.html

    【讨论】:

    • 来自a commentfind_element_by_*find_elements_by_* 在 Selenium 4.3.0 中被删除。改用 find_element。”.
    【解决方案2】:

    确保你有Selenium.By 进口

    from selenium.webdriver.common.by import By
    

    不要添加代码中的“by=”和“value=”部分。

    WebDriverWait

    使用WebDriverWait 方法定位元素也是一个更好的主意。运行以下命令:

    inputElement = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'su-input-group')))
    

    确保你也有这些导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-30
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多