【问题标题】:Selenium Webdriver, python - click 1st/2nd/3rd/etc element on a page?Selenium Webdriver,python - 单击页面上的第一个/第二个/第三个/等元素?
【发布时间】:2013-08-02 14:39:09
【问题描述】:

我为我公司的电子商务平台进行软件测试,并尝试自动化我们的结帐流程测试。对于多发货选项,每个订单项都有一个单独的“添加地址”链接。我可以轻松定位第一个,但我如何定位第二个/第三个/等?我不是开发人员,所以任何帮助都会非常有帮助。这是其中一个链接的 html 片段添加地址链接 -

<div class="editaddress eleven">
    <a class="add dialogify desktop" title="Add New Address" data-dlg-options="{ "width" :    "385px", "dialogClass" : "address-add-edit multishipping", "title" : "Add New Address"}" href="https://XXXXXXXXXXX/COShippingMultiple-EditAddress?i=bcvVIiaagN4ckaaada3w22QH7J"> Add New Address </a>

所有地址都是“editaddress 11”。不知道是谁决定的:-)

您能提供的任何帮助都会很棒。我正在努力学习webdriver。谢谢!

【问题讨论】:

  • 定位第一个的代码是什么样的?
  • 您好,您能多显示一些 html 代码吗?您需要一些定位器来唯一标识一个行项目而不是其他行项目;但是没有看到html,我们很难提出有用的建议。

标签: python selenium webdriver


【解决方案1】:

阅读docs,我认为函数名称不言自明。

#variable "driver" is the current selenium webdriver.

div = driver.find_element_by_css_selector('div.editaddress.eleven')

links = div.find_elements_by_css_selector('a.add.dialogify.desktop')

for link in links:
    #do_something

【讨论】:

    【解决方案2】:

    假设我们只知道“添加新地址”标题,我们可以(python 示例)创建一个匹配此规则的元素列表并遍历它。

    lines = driver.find_elements_by_css_selector("a[title='Add New Address']")

    【讨论】:

      【解决方案3】:

      你需要 xpath 选择器 给你:

      //a[@title='添加新地址'][i]

      Xpath 是一个相对选择器, // 告诉选择器在文档中的任何位置查找您列出的“a”类型元素,[@title='Add New Address"] 表示只返回那些标题为“添加新地址”的“a”类型元素。最后一部分是索引参考编号...我假设您有多个添加新地址元素,只要它们是相似的元素,将 i 替换为你想要的元素的#,相对于它在文档中的外观,从上到下。

      //a[@title='Add New Address'] - will get you all of the elements
      //a[@title='Add New Address'][1] - will get you the first
      //a[@title='Add New Address'][2] - will get you the second
      

      以此类推

      你应该做的是

      //count number of elements on the page and store them as an integer
      
      int numberofElements = selenium.getXPathCount("//a[@title='Add New Address']")
      
      //loop through the elements, grabbing each one and doing whatever you please with them
      
      for(i=0;i<numberofElements;i++){
        selenium.click("//a[@title='Add New Address']["+i+"]");
        //insert rest of commands you want selenium to do for every one of the elements that are   on the page
       }
      

      希望这会有所帮助 杰克

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 2020-01-29
        • 2019-01-12
        • 1970-01-01
        相关资源
        最近更新 更多