英文:
How to correctly use fn:tokenize when searching using xpath in selenium python
问题
以下是翻译好的部分:
正确调用 tokenize 函数在 Selenium 的 By.XPATH 选择器中的方法是什么?这里是一个看起来正确的片段,但出现了错误:“字符串 'tokenize(//font[@face='sans-serif' and @size='4'], '*')[2]' 不是有效的 XPath 表达式”。
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# //font[@face='sans-serif' and @size='4'] 返回:
# "Graphics * Unix * Networks * Fun"
# 使用 '*' 选择第三个标记
xpath: str = "tokenize(//font[@face='sans-serif' and @size='4'], '*')[2]"
with webdriver.Edge() as driver:
try:
driver.get("http://acme.com")
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath))
)
print(element.text)
except Exception as e:
print(f"找不到元素,原因是:{e}")
finally:
driver.quit()
有没有仅使用 XPath 的方法来在字符(或字符串)上进行标记化并选择第 n 项?是否有 Selenium 特定的语法?
英文:
What is the correct way to call the tokenize function in a By.XPATH selector in selenium. Here is a snippet of what seems correct but this errors with "The string 'tokenize(//font[@face='sans-serif' and @size='4'], "*")[2]' is not a valid XPath expression".
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# //font[@face='sans-serif' and @size='4'] returns:
# "Graphics * Unix * Networks * Fun"
# select 3rd token using "*"
xpath: str = "tokenize(//font[@face='sans-serif' and @size='4'], \"*\")[2]"
with webdriver.Edge() as driver:
try:
driver.get("http://acme.com")
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, xpath))
)
print(element.text)
except Exception as e:
print(f" Failed to find element due to: {e}")
finally:
driver.quit()
What is a xpath only method to tokenize on a character (or string) and select the nth item? Is there selenium specific syntaxt?
答案1
得分: 1
函数 fn:tokenize
是 XPath-2.0 的一部分。但在默认配置下,Selenium 只支持 XPath-1.0。
在这个 SO 问题中的答案声称可能有插件可以实现对 XPath-2.0 的支持。但我没有验证它们的有效性。
有没有仅使用 XPath 的方法来对字符(或字符串)进行分词并选择第 n 项?
我不知道任何可以在 XPath-1.0 中实现这一目标的函数。抱歉。
最接近的可能是使用 fn:translate(inputString, 'char', '
')
,它会将字符串按照每个 "char" 进行分割,创建每个子字符串之间的换行符。但这只适用于字符,而不适用于字符串。
英文:
The function fn:tokenize
is part of XPath-2.0. But selenium only supports XPath-1.0 in the default configuration.
The answers in this SO question claim that there may be plugins to realize XPath-2.0 support. But I haven't checked their validity.
> What is a xpath only method to tokenize on a character (or string) and select the nth item?
I don't know of any XPath-1.0 functions that can achieve that. Sorry.
The closest may be using a fn:translate(inputString,'char','
')
which splits the string by each "char" creating a newline between each substring. This only works for chars and not strings.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论