Python 循环中的同一链接打开

Python 循环中的同一链接打开,python,selenium-webdriver,Python,Selenium Webdriver,我是Python新手,正在尝试编写一个小代码来测试网站上的链接。。我创建了一本字典,如下所示: header_dropdown_links = { 'Features' : 'Features', 'Company' : 'Company | Values', 'Community' : 'Community | Open Sauce', 'Solutions' : 'Selenium Testin

我是Python新手,正在尝试编写一个小代码来测试网站上的链接。。我创建了一本字典,如下所示:

header_dropdown_links = {
            'Features' : 'Features', 
            'Company' : 'Company | Values',
            'Community' : 'Community | Open Sauce',
            'Solutions' : 'Selenium Testing | Solutions',
            'Resources' : 'Resources',
            'Enterprise' : 'Enterprise',
            'Sign Up' : 'Sign Up',
            'Docs' : 'Docs',
            'Pricing' : 'Pricing',
            'Login' : 'Login'      
       }
左边是链接名,右边是页面标题

我创建了以下表达式,以在循环中查找此链接的每个表达式,并将其与标题匹配。。 对于
标题中的链接\u下拉列表\u链接

header_link = '//nav[@id ="global"]//a[contains(text(),' + link + ')]'
        driver.find_element_by_xpath(header_link).click()
现在,当我运行这段代码时,我每次只点击参考资料链接,但它匹配所有标题,我不清楚为什么?有人能帮我吗

-------------------------编辑--------------------------------

我试图检查Glyph(3行图标)中的链接。 我写的代码是:

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import unittest

header_dropdown_links = {
        'Features' : 'Features', 
        'Company' : 'Company | Values',
        'Community' : 'Community | Open Sauce',
        'Solutions' : 'Selenium Testing | Solutions',
        'Resources' : 'Resources',
        'Enterprise' : 'Enterprise',
        'Sign Up' : 'Sign Up',
        'Docs' : 'Docs',
        'Pricing' : 'Pricing',
        'Login' : 'Login'      
    }

class SauceLabsHeader(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = 'https://saucelabs.com/'
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_sauce_labs_header(self):
        driver = self.driver

        for link in header_dropdown_links: 

            #opens SauceLabs Home Page
            driver.get(self.base_url)

            #clicks on Glyph for opening the drop down menu
            driver.find_element_by_class_name('hamburger').click()

            #finding link by xpath
            header_link = '//nav[@id ="global"]//a[contains(text(),' + link + ')]'
            driver.find_element_by_xpath(header_link).click()

            #verifying if the title matches
            expected_title = header_dropdown_links[link]
            try: self.assertRegexpMatches(driver.title,expected_title)
            except AssertionError as e: self.verificationErrors.append(str(e))


    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()
我得到的错误是:

   EE
======================================================================
ERROR: test_sauce_labs_header (__main__.SauceLabsHeader)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\-kuhu-\git\CS82A_Automation\src\SauceLabs_Glyph_WebDriver.py", line 42, in test_sauce_labs_header
    driver.find_element_by_xpath(header_link).click()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 232, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 664, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 175, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 166, in check_response
    raise exception_class(message, screen, stacktrace)
InvalidSelectorException: Message: The given selector //nav[@id ="global"]//a[contains(text(),Sign Up)] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //nav[@id ="global"]//a[contains(text(),Sign Up)] because of the following error:
SyntaxError: The expression is not a legal expression.
Stacktrace:
    at FirefoxDriver.annotateInvalidSelectorError_ (file:///c:/users/-kuhu-/appdata/local/temp/tmpjbvptb/extensions/fxdriver@googlecode.com/components/driver-component.js:10245)
    at FirefoxDriver.prototype.findElementInternal_ (file:///c:/users/-kuhu-/appdata/local/temp/tmpjbvptb/extensions/fxdriver@googlecode.com/components/driver-component.js:10276)
    at FirefoxDriver.prototype.findElement (file:///c:/users/-kuhu-/appdata/local/temp/tmpjbvptb/extensions/fxdriver@googlecode.com/components/driver-component.js:10280)
    at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/-kuhu-/appdata/local/temp/tmpjbvptb/extensions/fxdriver@googlecode.com/components/command-processor.js:12274)
    at DelayedCommand.prototype.executeInternal_ (file:///c:/users/-kuhu-/appdata/local/temp/tmpjbvptb/extensions/fxdriver@googlecode.com/components/command-processor.js:12279)
    at DelayedCommand.prototype.execute/< (file:///c:/users/-kuhu-/appdata/local/temp/tmpjbvptb/extensions/fxdriver@googlecode.com/components/command-processor.js:12221)

======================================================================
ERROR: test_sauce_labs_header (__main__.SauceLabsHeader)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\-kuhu-\git\CS82A_Automation\src\SauceLabs_Glyph_WebDriver.py", line 52, in tearDown
    self.assertEqual([], self.verificationErrors)
AssertionError: Lists differ: [] != ["Regexp didn't match: 'Featur...

Second list contains 2 additional elements.
First extra element 0:
Regexp didn't match: 'Features' not found in u'Resources'

- []
+ ["Regexp didn't match: 'Features' not found in u'Resources'",
+  "Regexp didn't match: 'Enterprise' not found in u'Resources'"]

----------------------------------------------------------------------
Ran 1 test in 52.697s

FAILED (errors=2)

你确定这部分是正确的吗-

header_link = '//nav[@id ="global"]//a[contains(text(),link)]'
难道不是吗-

header_link = '//nav[@id ="global"]//a[contains(text(),"' + link + '")]'
您希望
link
作为contains中的字符串,还是希望每个链接中都包含文本,如
Resources
那里?

仍然显示错误:

E
======================================================================
ERROR: test_sauce_labs_header (__main__.SauceLabsHeader)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\-kuhu-\git\CS82A_Automation\src\SauceLabs_Glyph_WebDriver.py", line 43, in test_sauce_labs_header
    driver.find_element_by_xpath(header_link).click()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 232, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 664, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 175, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 166, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//nav[@id =\"global\"]//a[contains(text(),\"Sign Up\")]"}
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_ (file:///c:/users/-kuhu-/appdata/local/temp/tmpivizdh/extensions/fxdriver@googlecode.com/components/driver-component.js:10271)
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///c:/users/-kuhu-/appdata/local/temp/tmpivizdh/extensions/fxdriver@googlecode.com/components/driver-component.js:603)

----------------------------------------------------------------------
Ran 1 test in 94.708s

FAILED (errors=1)
E
======================================================================
错误:测试\u酱汁\u实验室\u标头(\u主\u.SauceLabsHeader)
----------------------------------------------------------------------
回溯(最近一次呼叫最后一次):
文件“C:\Users \-kuhu-\git\CS82A \-u Automation\src\SauceLabs \-u Glyph \-u WebDriver.py”,第43行,在test \-u sause \-u labs \-u标题中
驱动程序。通过xpath(标题链接)查找元素。单击()
文件“C:\Python27\lib\site packages\selenium\webdriver\remote\webdriver.py”,第232行,在find\u element\u by\u xpath中
返回self.find_元素(by=by.XPATH,value=XPATH)
文件“C:\Python27\lib\site packages\selenium\webdriver\remote\webdriver.py”,第664行,在find\u元素中
{'using':by'value':value})['value']
文件“C:\Python27\lib\site packages\selenium\webdriver\remote\webdriver.py”,第175行,执行
self.error\u handler.check\u响应(响应)
文件“C:\Python27\lib\site packages\selenium\webdriver\remote\errorhandler.py”,第166行,在check\u响应中
引发异常类(消息、屏幕、堆栈跟踪)
NoSuchElementException:消息:找不到元素:{“方法”:“xpath”,“选择器”:”//nav[@id=\“global\”]//a[contains(text(),\“Sign Up\”)]“}
堆栈跟踪:
在FirefoxDriver.prototype.findelement内部(file:///c:/users/-kuhu-/appdata/local/temp/tmpivizdh/extensions/fxdriver@googlecode.com/组件/驱动程序组件(js:10271)

在fxdriver.Timer.prototype.setTimeout/你能在使用前打印
标题链接吗?你能解释一下这里三个引号的意义吗?它实际上是xpath中
包含
函数的双引号,xpath试图将每个
资源
等解析为变量而不是字符串,这与任何其他语言都是一样的。当我们添加双引号时,xpath正确地开始将第二个参数识别为字符串。对于某些组件,函数是否成功?请尝试使用xpath-
。//nav[@id=“global”]//a[contains](text(),““+link+”)”””
很抱歉,您在此之前发布的解决方案似乎有效…查找注册时出现一些问题…因此,在此处和之前发布的代码中注册失败..尝试修复..非常感谢您的帮助!:)
E
======================================================================
ERROR: test_sauce_labs_header (__main__.SauceLabsHeader)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\-kuhu-\git\CS82A_Automation\src\SauceLabs_Glyph_WebDriver.py", line 43, in test_sauce_labs_header
    driver.find_element_by_xpath(header_link).click()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 232, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 664, in find_element
    {'using': by, 'value': value})['value']
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 175, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 166, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//nav[@id =\"global\"]//a[contains(text(),\"Sign Up\")]"}
Stacktrace:
    at FirefoxDriver.prototype.findElementInternal_ (file:///c:/users/-kuhu-/appdata/local/temp/tmpivizdh/extensions/fxdriver@googlecode.com/components/driver-component.js:10271)
    at fxdriver.Timer.prototype.setTimeout/<.notify (file:///c:/users/-kuhu-/appdata/local/temp/tmpivizdh/extensions/fxdriver@googlecode.com/components/driver-component.js:603)

----------------------------------------------------------------------
Ran 1 test in 94.708s

FAILED (errors=1)