Selenium(Python)检查标签旁边的参数并插入值或选择一个选项

2024-10-01 09:19:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如果希望创建一个通用代码(使用Selenium),该代码将查找标签,并在标签输入(或选择)标记旁边查找并插入值

主要功能:

for l in label: 
        try:
            xpathInput = "//label[contains(.,'{}')]/following::input".format(l)

            checkXpathInput, pathInput= check_xpath(browser,xpathInput)

            if checkXpathInput is True:
                pathInput.clear()
                pathInput.send_keys("\b{}".format(value))
                break

            for op in option:

                xpathSelect = "//label[contains(.,'{}')]/following::select/option[text()='{}']".format(l,op)
                checkXpathSelect, pathSelect= check_xpath(browser,xpathSelect)

                if checkXpathSelect is True:
                    pathSelect.click()
                    break


        except:
            print("Can't match: {}".format(l)) 

路径检查器:

def check_xpath(browser,xpath):
    try:
        path = browser.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True , path

当前的问题是什么

  • 我需要,如果标签将是例如标题,代码将检查“标题”标签旁边是否没有input标记,然后他将去检查标签“标题”和e.t.c.旁边是否有select标记

在我的当前输入中,他将找到标签“Title”,然后将值填充到下一个输入中(这是不正确的,因为“Title”使用的是SELECT标记)


Tags: 代码in标记browsertrueformat标题for
1条回答
网友
1楼 · 发布于 2024-10-01 09:19:38

我会利用find_elements_by_xpath返回已找到元素的列表,而空列表是错误的这一事实。因此,您不需要try/except和返回booltuple值(这不是最佳行为)的函数

用一些html源代码示例给出一个好的答案会更容易,但我假设您想做的是:

def handle_label_inputs(label, value):
    # if there is a such label, this result won't be empty
    found_labels = driver.find_elements_by_xpath('//label[contains(.,"{}")]'.format(label))

    # if the list is not empty
    if found_labels:
        l = found_labels[0]
        # any options with the given value as text
        following_select_option_values = l.find_elements_by_xpath('./following::select//option[text()="{}"]'.format(value))
        # any inputs next to the label
        following_inputs = l.find_elements_by_xpath('./following::input')

        # did we find an option?
        if following_select_option_values:
            following_select_option_values[0].click()
        # or is there an input?
        elif following_inputs:
            in_field = following_inputs[0]
            in_field.clear()
            in_field.send_keys(value)
        else:
            print("Can't match: {} - {}".format(label, value))

driver.get('http://thenewcode.com/166/HTML-Forms-Drop-down-Menus')
handle_label_inputs('State / Province / Territory', 'California')

我不知道你使用的页面有多整洁,但是如果做得好,那么你的标签应该有一个for="something"属性。如果是这种情况,那么您只需查找与标签相关的元素,并确定其标记是否为input(或select):

related_element_if_done_properly = driver.find_elements_by_xpath('//*[@id="{}"]'.format(label_element.get_attribute("for")))
if related_element_if_done_properly:
    your_element = related_element_if_done_properly[0]
    is_input = your_element.tagname.lower() == "input"
else:
    print('Ohnoes')

相关问题 更多 >