【问题标题】:How to correctly pass basic auth (every click) using Selenium and phantomjs webdriver如何使用 Selenium 和 phantomjs webdriver 正确传递基本身份验证(每次点击)
【发布时间】:2016-09-16 19:59:56
【问题描述】:

我正在使用 Selenium Webdriver 运行一些单元测试。

我有一个使用 webdriver.Firefox() 成功运行的完整测试,这里是设置:

def setUp(self):
    self.driver = webdriver.Firefox()
    self.driver.implicitly_wait(30)
    self.base_url = "http://www.nike.com"
    self.verificationErrors = []
    self.accept_next_alert = True

测试成功运行,但是我必须多次手动输入基本身份验证才能继续进行测试。

为了绕过基本身份验证并让整个测试真正自动化,我已经从 Firefox 切换到 phantomjs,因为听起来您可以通过每次点击()传递基本身份验证

这是我切换到 phantomjs 后的设置:

def setUp(self):
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantoms.page.settings.userName"] = ("testuser")
    dcap["phantoms.page.settings.userPassword"] = ("testpass")
    self.driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=['--ignore-ssl-errors=true'])
    self.driver.implicitly_wait(30)
    self.base_url = "http://www.nike.com
    self.verificationErrors = []
    self.accept_next_alert = True

但我收到以下错误:

NoSuchElementException: Message: {"errorMessage":"Unable to find
element with xpath '(//button[@type='button'])[2]'","request":
{"headers":{"Accept":"application/json","Accept-Encoding":"identity",
"Connection":"close","Content-Length":"113","Content- Type":"application/json;charset=UTF-8",
"Host":"127.0.0.1:58025","UserAgent":"Pythonurllib/2.7"},"httpVersion":"1.1",
"method":"POST","post":"{\"using\": \"xpath\", \"sessionId\": \"c2fa02e0-1df0-11e6-a2ad-c325e56df16d\",
\"value\": \"(//button[@type='button'][2]\"}","url":"/element","urlParsed":
{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"",
"password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":    
["element"]},"urlOriginal":"/session/c2fa02e0-1df0-11e6-a2ad-c325e56df16d/element"}}

我不确定这个错误是否只是 phantomjs 和 firefox 之间的差异,或者我只是错误地传递了身份验证。

【问题讨论】:

    标签: python selenium-webdriver phantomjs


    【解决方案1】:

    以下是使用 PhantomJS 和 Selenium 在标头中定义基本身份验证令牌的方法:

    from selenium import webdriver
    from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
    import base64
    
    authentication_token = "Basic " + base64.b64encode(b'username:password')
    
    capa = DesiredCapabilities.PHANTOMJS
    capa['phantomjs.page.customHeaders.Authorization'] = authentication_token
    driver = webdriver.PhantomJS(desired_capabilities=capa)
    
    driver.get("http://...")
    

    【讨论】:

    • 谢谢,这会在每次连续点击时通过 authentication_token 吗?
    • 是的,如果点击是指向新页面的链接,但我不确定 Ajax 调用。
    • 我接受了您的回答,但这并没有最终解决我的问题,因为从多个主机请求基本身份验证(页面中的嵌入内容需要它自己的基本身份验证)。我不确定有没有办法使用 Selenium 以这种方式将凭据传递给多个主机,我认为 phantomjs 会提供一种解决方法,但我想不会。
    猜你喜欢
    • 2013-08-15
    • 1970-01-01
    • 2012-03-04
    • 2011-08-06
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多