Xpath doesn't work with string, which have quotes. Chrome

I have the text: var1 = 'ТСЖ "ВОЛГОГРАДСКИЙ ПР-Т 50-1, 52-1, 52-2, 56-1, 56-2, 58-1, 58-3, 60-2, 64-1, 64-2, 66-2, ВОЛЖСКИЙ 21"'

And I have xpath: driver.find_element_by_xpath("//a[text()='"+var1+"']/ancestor::div[contains(@class,'chakra-stack') and contains(@class,'css-1oap1wr')]/following-sibling::div/descendant::button[text()='Отклонить']").click() - It does'nt work

//a[text()='ТСЖ "ВОЛГОГРАДСКИЙ ПР-Т 50-1, 52-1, 52-2, 56-1, 56-2, 58-1, 58-3, 60-2, 64-1, 64-2, 66-2, ВОЛЖСКИЙ 21"']/ancestor::div[contains(@class,'chakra-stack') and contains(@class,'css-1oap1wr')]/following-sibling::div/descendant::button[text()='Отклонить'] - But this work!

Python writes me :selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[text()='ТСЖ "ВОЛГОГРАДСКИЙ ПР-Т 50-1, 52-1, 52-2, 56-1, 56-2, 58-1, 58-3, 60-2, 64-1, 64-2, 66-2, ВОЛЖСКИЙ 21"']/ancestor::div[contains(@class,'chakra-stack') and contains(@class,'css-1oap1wr')]/following-sibling::div/descendant::button[text()='Отклонить']"}

But if I Cut xpath from error messeage and put it like xpath in console of Chrome - element would finded.

Element absoulutle visible and already loaded. Sory for my English.

1 answer

  • answered 2021-01-19 20:06 DMart

    You need to escape the quotes. Try either this:

    var1 = 'ТСЖ "ВОЛГОГРАДСКИЙ ПР-Т 50-1, 52-1, 52-2, 56-1, 56-2, 58-1, 58-3, 60-2, 64-1, 64-2, 66-2, ВОЛЖСКИЙ 21"'
    
    driver.find_element_by_xpath('//a[text()=\''+var1+'\']/ancestor::div[contains(@class,\'chakra-stack\') and contains(@class,\'css-1oap1wr\')]/following-sibling::div/descendant::button[text()=\'Отклонить\']').click()
    

    or this

    var1 = 'ТСЖ "ВОЛГОГРАДСКИЙ ПР-Т 50-1, 52-1, 52-2, 56-1, 56-2, 58-1, 58-3, 60-2, 64-1, 64-2, 66-2, ВОЛЖСКИЙ 21"'
    
    #replace the double quotes with \"
    var1 = var1.replace('"', '\\"')
    driver.find_element_by_xpath("//a[text()='"+var1+"']/ancestor::div[contains(@class,'chakra-stack') and contains(@class,'css-1oap1wr')]/following-sibling::div/descendant::button[text()='Отклонить']").click()