【问题标题】:Iterate through a group of elements with python selenium使用 python selenium 遍历一组元素
【发布时间】:2021-07-30 08:27:00
【问题描述】:

我在 WordPress 中有一个网站,我需要在其中编辑许多页面。 以下是它们的列表: screenshot

我需要遍历每个页面:'apple' 'banana' 等 单击它并制作一些版本。 但是不知道该怎么做,因为当我尝试通过 Xpath 进行操作时,id 差异很大:

apple - //*[@id="post-11515"]/td[1]/strong/a
banana - //*[@id="post-11501"]/td[1]/strong/a

这就是单个“a href”的 html 的样子:

<a class="row-title" href="https://address.pl/wp-admin/post.php?post=11216&amp;action=edit"aria-label="„apple” (Edycja)">apple</a>

你知道我可以如何循环遍历这些项目吗?

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    您可以存储所有a 标记元素,然后在for 循环中进行迭代。喜欢-

        options = driver.find_elements_by_xpath(".../a")
        ''' Can also use driver.find_elements_by_class_name("a") 
            if they are only elements in a tag '''
        for opt in options:
               #code to make changes
               driver.switch_to.default_content()
    

    【讨论】:

      【解决方案2】:

      查看 Apple 和 Banana 的这两个 id:-

      apple - //*[@id="post-11515"]/td[1]/strong/a
      banana - //*[@id="post-11501"]/td[1]/strong/a
      

      您可以构造一个 xpath 来表示所有这些,然后可以进行索引以迭代:-

      xpath

      //*[contains(@id, 'post')]/td[1]/strong/a
      

      然后像这样点击它:

      import time
      for item in driver.find_elements(By.XPATH, "//*[contains(@id, 'post')]/td[1]/strong/a"):
          item.click()
          time.sleep(.5)
      

      【讨论】:

        猜你喜欢
        • 2015-01-16
        • 2020-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-18
        • 2021-11-08
        • 1970-01-01
        相关资源
        最近更新 更多