【问题标题】:Making flexible XPath for Selenium (Python)为 Selenium (Python) 制作灵活的 XPath
【发布时间】:2016-08-12 20:35:50
【问题描述】:

我正在尝试使用 selenium 和 python 将 web 元素的文本内容设置为字符串。

代码: monthname = browser.find_element_by_xpath("//*[@id='monthRow-7']/td[1]").text 有效,但我希望能够更改 monthRow-7 以包含不同的数字。

我的想法是询问用户一个月(1-12),他们输入的内容存储到一个名为monthnum的字符串中。然后我可以将字符串monthnum连接到xpath中以更改monthRow的数量。前任。用户在提示输入月份编号时输入 9,因此将 monthRow-7 更改为 monthRow-9。

我尝试过: monthname = browser.find_element_by_xpath(("\"//*[@id='monthRow-") + monthnum + ("']/td[1]\"")).text 其中monthnum 是用户输入设置的字符串。

但这给了我一个错误,上面写着:

“消息:无效选择器:由于以下错误,无法使用 xpath 表达式“//*[@id='monthRow-7']/td[1]”定位元素: TypeError: 无法对“文档”执行“评估”:结果不是节点集,因此无法转换为所需的类型。”

错误中列出的 xpath 表达式与我在代码中实际使用的 xpath 表达式相同。有什么方法可以通过将 xpath 的位分配给变量来更改 xpath?

【问题讨论】:

    标签: python xml selenium xpath concatenation


    【解决方案1】:

    我会为此使用string formatting

    monthnum = 7
    monthname = browser.find_element_by_xpath("//*[@id='monthRow-{}']/td[1]".format(monthnum)).text
    

    这里的{}会被monthnum的值代替。

    我不太确定你在尝试什么,但我认为你的解决方案应该是这样的:

    monthname = browser.find_element_by_xpath("//*[@id='monthRow-" + monthnum + "']/td[1]").text
    

    所有这些圆括号和额外的引号都应该是不必要的。

    【讨论】:

    • 成功了,非常感谢!我是 Python 新手,甚至不知道 .format 存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2019-09-24
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多