Chandral
Chandral

Reputation: 448

How do I pass a string variable with apostrophe (') in a Xpath for Python-Selenium?

I have a web table where I need to click the edit template icon (the one that looks like a notepad in the image below) for each row. The table looks like this.

My code checks for the text and then clicks the icon. I don't have any trouble with the first two but the last one gives an error of invalid xpath expression because of the apostrophe. Below is the code that I am using. The list 'form_titles' is created dynamically by detecting the .xsn files that I need to upload from my local folder to each of these forms one by one. Each 'form title' has its own unique .xsn file and I use a spreadsheet containing a pre-compiled list for referring each .xsn file to its 'form title'.

form_titles = ["3.08 Incident Estimates", "3.09 Quotation by the Consultant", "3.10 Employer's Assessment"]

for form in form_titles:    
    try:
        WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.XPATH, "//td[contains(text(),'%s')]" % (form))))
    finally:
        browser.find_element_by_xpath("//td[contains(text(),'%s')]/following-sibling::td/a[contains(@onclick, 'editProjectFormType')]" % (form)).click()
        time.sleep(30)

Upvotes: 2

Views: 738

Answers (1)

Saurabh Gaur
Saurabh Gaur

Reputation: 23805

You should use \ to escape "" char as below :-

form_titles = ["3.08 Incident Estimates", "3.09 Quotation by the Consultant", "3.10 Employer's Assessment"]

for form in form_titles:    
    try:
        WebDriverWait(browser, 60).until(EC.presence_of_element_located((By.XPATH, "//td[contains(text(),\"%s\")]" % (form))))
    finally:
        browser.find_element_by_xpath("//td[contains(text(),\"%s\")]/following-sibling::td/a[contains(@onclick, 'editProjectFormType')]" % (form)).click()
        time.sleep(30)

Hope it helps...:)

Upvotes: 2

Related Questions