【问题标题】:Selecting Element followed by text with Selenium WebDriver使用 Selenium WebDriver 选择元素后跟文本
【发布时间】:2012-07-09 12:04:32
【问题描述】:

我正在使用 Selenium WebDriver 和 Python 绑定来自动化一些单调的 WordPress 任务,到目前为止,它一直非常简单。我正在尝试选择一个复选框,但我可以识别它的唯一方法是通过它后面的文本。这是 HTML 的相关部分:

<li id="product_cat-52">
    <label class="selectit">
       <input value="52" type="checkbox" name="tax_input[product_cat][]" id="in-product_cat-52"> polishpottery
    </label>
</li>

我在脚本中识别此复选框的唯一信息是字符串“polishpottery”。有没有办法只知道后面的文本来选择该复选框?

【问题讨论】:

    标签: python selenium webdriver selenium-chromedriver


    【解决方案1】:

    正则表达式——可能不是最好的解决方案,但它应该可以工作。

    import re
    
    def get_id(str, html_page): # str in this case would be 'polishpottery'
        return re.search(r'<input[^<>]*?type="checkbox"[^<>]*?id="([A-Za-z0-9_ -]*?)"[^<>]*?> ?' + str, html_page).group(1)
    
    id = get_id('polishpottery', html)
    checkbox = driver.find_element_by_id(id)
    checkbox.toggle()
    
    # Or, more minimallistically:
    driver.find_element_by_id(get_id('polishpottery', html)).toggle()
    

    输出:

    >>> print(html)
    <li id="product_cat-52">
        <label class="selectit">
           <input value="52" type="checkbox" name="tax_input[product_cat][]" id="in-product_cat-52"> polishpottery
        </label>
    </li>
    >>> get_id('polishpottery', html)
    'in-product_cat-52'
    

    【讨论】:

      【解决方案2】:

      我建议尝试找到更多方法来选择复选框。例如,您可以使用 browser.find_element_by_id(id) 根据其 id 选择 li 标签。您也可以使用 browser.find_element_by_name(name) 根据名称进行选择。

      或者,如果你真的不能,你可以使用 selenium + BeautifulSoup 选择文本。

      soup = BeautifulSoup(browser.page_source)
      text = soup.find('input', re.compile=" polishpottery")
      checkbox = text.parent 
      # it might not exactly be parent, but you can play around with
      # navigating the tree.
      

      希望这会有所帮助!

      【讨论】:

        【解决方案3】:

        正如@sherwin-wu 已经说过的,你应该找到一种方法来根据 id 或 name 或 class(很可能是它们的组合)来选择你想要的东西。在您的示例中,似乎有足够的可能性这样做,尽管我不知道页面的其余部分通常是什么样子。

        话虽如此,使用 XPath 选择器可以满足您的要求

        driver.find_element_by_xpath("//li/label/input[contains(..,'polishpottery')]")
        

        【讨论】:

        • 看起来 XPath 是答案,我最终使用了 driver.find_element_by_xpath("//label[contains(text(),'polishpottery')]/input") 我无法按 ID 选择的原因是我正在处理一堆可能已经预先输入的类别给定任何 ID,但我得到的唯一信息是类别名称。感谢您的回答 - 这正是我所需要的!
        • 太好了,几乎是等价的。因此,请使用您认为更具可读性的任何内容!
        猜你喜欢
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 2014-09-21
        • 2020-12-19
        相关资源
        最近更新 更多