python selenium firefox,特殊字符@用于身份验证弹出窗口

时间:2018-06-22 08:21:18

标签: python selenium

我正在尝试使用python Selenium登录到需要身份验证凭据的网页。
与示例here不同 我的用户名是一个电子邮件地址,因此包含“ @”字符(我正在使用Python)。

from selenium import webdriver
driver = webdriver.Firefox()
webpage = 'http://somewhere.com/cgi-bin/dirwrap.cgi?template=template&path=news'
username = 'myname@mymailbox.com'
password = 'mypassword'
url = username + ':' + password + '@' + webpage
print(url)
driver.get(url)

输出是

myname@mymailbox.com:mypassword@http://somewhere.com/cgi-bin/dirwrap.cgi?template=template&path=news
Traceback (most recent call last):
File "question.py", line 12, in <module>
  driver.get(url)
File "/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 324, in get
  self.execute(Command.GET, {'url': url})
File "/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
  self.error_handler.check_response(response)
File "/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
  raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: Malformed URL: myname@mymailbox.com:mypassword@http://somewhere.com/cgi-bin/dirwrap.cgi?template=template&path=news is not a valid URL.

我认为问题出在额外的'@'字符上。如何放入而不创建格式错误的URL?

1 个答案:

答案 0 :(得分:0)

您没有正确的网址,它必须为http://username:password@url,但是您有username:password@http://url

尝试

webpage = 'somewhere.com/cgi-bin/dirwrap.cgi?template=template&path=news'
username = 'myname@mymailbox.com'
password = 'mypassword'

url = 'http://{}:{}@{}'.format(username, password, webpage)

输出

http://myname@mymailbox.com:mypassword@somewhere.com/cgi-bin/dirwrap.cgi?template=template&path=news

但是我认为这会引起问题,因为例如,您有两种@更好的方法是使用send_keys

webpage = 'http://somewhere.com/cgi-bin/dirwrap.cgi?template=template&path=news'

driver.get(url)

email_input = driver.find_element_by_xpath('email input xpath')
email_inpit.clear()
email_input.send_keys(username)

pwd_input = driver.find_element_by_xpath('password input xpath')
pwd_inpit.clear()
pwd_input.send_keys(password)

# and after this you need to click on `ok` btn