【问题标题】:How to fix 'Message: Unable to locate element: {"method":"name","selector":"username"}'如何修复'消息:无法找到元素:{“method”:“name”,“selector”:“username”}'
【发布时间】:2019-07-14 06:15:00
【问题描述】:

我的 Python 代码在我的 PC 上运行良好, 但是当我将它上传到服务器时它显示错误。 请看代码很容易阅读

从 pyvirtualdisplay 导入显示 从硒导入网络驱动程序 进口时间

使用 Display():

browser = webdriver.Firefox()


try:

    browser.set_window_size(1080,800)

    browser.get('https://www.instagram.com/accounts/login')

    print (browser.title)

    time.sleep(5)

    # i used the screenshot to cheek the problem , but the screenshot is totally
    # blank (just a whit screen )  

    browser.save_screenshot("screenshot.png")
    print("clicked..!")
    browser.find_element_by_name("username").send_keys('*****')
    browser.find_element_by_name("password").send_keys('*****')

finally:
    browser.quit()

登录 • Instagram 点击..!

Traceback (most recent call last):
  File "/home/Sourabh58/bot1.py", line 25, in <module>
    browser.find_element_by_name("username").send_keys('be_fully_motivated')
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 365, in find_element_by_name
    return self.find_element(by=By.NAME, value=name)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
    'value': value})['value']
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/usr/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"name","selector":"username"}

【问题讨论】:

  • 只是等待页面加载我认为在服务器页面没有加载。添加一个方法来检查页面是否加载,然后执行操作。

标签: python selenium-webdriver pythonanywhere


【解决方案1】:

使用time.sleep()anti-pattern 的某种形式,因为即使元素更快地出现在DOM 中,您的测试也会等待5 秒。

考虑重构您的代码以改用Explicit Waits,这样 WebDriver 将轮询 DOM 以了解元素是否存在(或不存在),并在找到元素后立即继续。

建议的代码更改:

driver.get('https://www.instagram.com/accounts/login')

username = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.NAME, 'username')))
username.send_keys("****")
password = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.NAME, 'password')))
password.send_keys("****")

10 stanza 代表 10 秒的最大等待时间,您可以根据您的测试场景、网络带宽、应用程序响应时间等增加/减少它。

更多信息:How to use Selenium to test web applications using AJAX technology

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多