How to pass Python variable to XPath expression?

How to pass Python variable to XPath expression?

I am currently working on a script that prints the ID of an Web Element based on a given text. Up till now I managed to do this:

I am currently working on a script that prints the ID of an Web Element based on a given text. Up till now I managed to do this:

wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(), 'my_text')]"))
ID = browser.find_element_by_xpath("//*[contains(text(), 'my_text')]").get_attribute("id")
print(ID)

The code works fine, but I want to change it so it can be used for strings other than "my_text".

How can I pass a variable to that function? Something like this:

variable = 'my_text'
wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(), variable)]"))
ID = browser.find_element_by_xpath("//*[contains(text(), variable)]").get_attribute("id")
print(ID)

This way I could assign any text to the variable and use the same function every time.

Thanks!

python selenium

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Python Selenium Introduction & Installation

This is our first article with video training on Python Selenium, in this article we are going to talk about Introduction & Installation of Selenium. we are

Python Selenium Web Elements Introduction

This is our second article on Python Selenium, in this article we are going to learn about Web Elements Introduction in Python Selenium. in the first

Python Selenium Web Driver Navigation Command

Python Selenium Web Driver Navigation Command - In this article we are going to learn about Selenium Web Driver Navigation Command in Python.so using Selenium

Selenium with Python

Selenium with Python

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.