如何使用python ansdselenium登录网页


driver.find_element_by_id('username').send_keys('945412')
print 'username entered'
driver.find_element_by_name('password').send_keys('mns347')
print 'password entered'
driver.find_element_by_name("submit").click()
print 'submit'

但它抛出错误

Traceback (most recent call last):
File "C:UsersSSDesktoppython-mpsele_sample.py", line 17, in <module>
driver.find_element_by_id('username').send_keys('945412')
File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", line 978, in find_element
'value': value})['value']
File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:Python27libsite-packagesseleniumwebdriverremoteerrorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"username"}
(Session info: chrome=70.0.3538.102)
(Driver info: chromedriver=2.44.609538 (b655c5a60b0b544917107a59d4153d4bf78e1b90),platform=Windows NT 6.3.9600 x86_64)

您可以添加显式等待来等待元素被加载。

username= WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.ID, "username"))
)
username.send_keys('945412')

我看不出您的代码中有任何错误。但根据您的错误消息,没有id为username的字段。

请确保您的网站上确实有一个带有id用户名的字段。

例如,githubs用户名字段定义如下

<input name="login" id="login_field" class="form-control input-block" tabindex="1" autocapitalize="off" autocorrect="off" autofocus="autofocus" type="text">

在这种情况下,您必须使代码适应这种情况。这看起来像

driver.find_element_by_id('login_field').send_keys('945412')

因为字段包含id="login_field">

import the by module and try this instead,
from selenium.webdriver.common.by import By
element = driver.find_element(by=By.ID, value="username")
element.send_keys('945412')
use wait like below, if the above code doesn't work username= WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.ID, "username"))
);
username.send_keys('945412.')

您需要安装chromedriver和chrome。如果需要,您可以更改其他浏览器的这些设置。这对我来说很好。

from selenium import webdriver
browser = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver")
browser.get('<login_url>')
username = browser.find_element_by_name("<username_name_tag>")
password = browser.find_element_by_name("<password_name_tag>")
username.send_keys("<username>")
password.send_keys("<password>")
browser.find_element_by_id("<login_button_id>").click()

相关内容

  • 没有找到相关文章

最新更新