有没有方法通过xpath regex从循环中传递变量来查找元素?

2024-09-25 08:38:56 发布

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

我试图通过Xpath()传递string的值来查找元素,以获得对属性值部分的搜索和匹配。我该怎么做

我在Python3.7和selenium库上试过,找不到从循环传递值的方法。我尝试了以下几点,但是没有成功

datasets = [  'ds_pos_retail_outlet','ds_pos_retail_fullset', 'ds_pos_retail_ProfitCenter','ds_pos_retail_Section']

for x in datasets :

    refreshNow= driver.find_element_by_xpath('//button[starts-with(@aria-describedby, x) and @title="Refresh now"]')
    refreshNow.click()
    time.sleep(8)

我想选择并单击一个属性值为通过regex match传递的节点


Tags: 方法pos元素string属性seleniumdssection
2条回答

一种方法是使用format()

xpath = '//button[starts-with(@aria-describedby, {}) and @title="Refresh now"]'.format(x)
refreshNow= driver.find_element_by_xpath(xpath)

除了format函数之外,还可以使用简单的字符串连接

refreshNow = driver.find_element_by_xpath('//button[starts-with(@aria-describedby, ' + x + ') and @title="Refresh now"]')

相关问题 更多 >