Не передать текст с кавычками в xpath локатор selenium
Есть текст.
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()
Не находит элемент.
НО запрос
//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()='Отклонить']
Находит нужный элемент. ХОТЯ ОНИ ИДЕНТИЧНЫ.
С переменной python выдает следующее в консоли:
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()='Отклонить']"}
И если скопировать запрос, на который ругается питон и попробовать найти им элемент в хроме - ИЩЕТ!
Вопрос. Как передать переменную, чтобы элемент искало. Элемент ТОЧНО находится в видимости и ТОЧНО уже загрузился. Спасибо.
Ответы (1 шт):
Автор решения: gil9red
→ Ссылка
Добавил форматирование текста.
Работает?
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(f"//a[text()='{var1}']/ancestor::div[contains(@class,'chakra-stack') and contains(@class,'css-1oap1wr')]/following-sibling::div/descendant::button[text()='Отклонить']").click()
UPD.
Открыл локально кусок HTML и xpath нашел элемент
from selenium import webdriver
driver = webdriver.Firefox()
driver.get(r'C:\Users\ipetrash\Projects\SimplePyScripts\_FOO_TEST_TEST\1.html')
nameOrg = 'ТСЖ "ВОЛГОГРАДСКИЙ ПР-Т 50-1, 52-1, 52-2, 56-1, 56-2, 58-1, 58-3, 60-2, 64-1, 64-2, 66-2, ВОЛЖСКИЙ 21"'
text = "//a[text()='{nameOrg}']/ancestor::div[contains(@class,'chakra-stack') and contains(@class,'css-1oap1wr')]/following-sibling::div/descendant::button[text()='Отклонить']".format(nameOrg=nameOrg)
print(text)
el = driver.find_element_by_xpath(text)
print(el)
