如何在使用 Selenium Webdriver 查找元素时正确使用 '{}'.format()
How to properly use '{}'.format() while finding an element with Selenium Webdriver
我正在编写一个使用 name_parameter 在网站内搜索的函数,但我确定我拼错了某些内容,并且无法通过输入获得正确的按钮。我知道 XPATH 具有正确的结构,因为如果我对 page_name 进行硬编码,那么我会得到预期的结果
def change_user(self, page_name):
select_user = WebDriverWait(self.driver, 4).until(
EC.element_to_be_clickable((
By.XPATH, f'//div/div/div/span[contains(text(), {0} )]'.format(page_name)))
)
time.sleep(random.uniform(0.15, 0.5))
select_user.click()
此函数的硬编码实际工作版本如下:
def change_user(self, page_name):
select_user = WebDriverWait(self.driver, 4).until(
EC.element_to_be_clickable((
By.XPATH, f'//div/div/div/span[contains(text(), "Carl Rogers" )]'))
)
time.sleep(random.uniform(0.15, 0.5))
select_user.click()
我将此参考用于语法 https://www.w3schools.com/python/ref_string_format.asp
您可以使用 f"String {variable}"
或 "String {0}".format(variable)
,但您同时使用了两者。只需删除字符串开头的 f
。
试试
path = r'//div/div/div/span[contains(text(), "{}" )]'.format('test')
我正在编写一个使用 name_parameter 在网站内搜索的函数,但我确定我拼错了某些内容,并且无法通过输入获得正确的按钮。我知道 XPATH 具有正确的结构,因为如果我对 page_name 进行硬编码,那么我会得到预期的结果
def change_user(self, page_name):
select_user = WebDriverWait(self.driver, 4).until(
EC.element_to_be_clickable((
By.XPATH, f'//div/div/div/span[contains(text(), {0} )]'.format(page_name)))
)
time.sleep(random.uniform(0.15, 0.5))
select_user.click()
此函数的硬编码实际工作版本如下:
def change_user(self, page_name):
select_user = WebDriverWait(self.driver, 4).until(
EC.element_to_be_clickable((
By.XPATH, f'//div/div/div/span[contains(text(), "Carl Rogers" )]'))
)
time.sleep(random.uniform(0.15, 0.5))
select_user.click()
我将此参考用于语法 https://www.w3schools.com/python/ref_string_format.asp
您可以使用 f"String {variable}"
或 "String {0}".format(variable)
,但您同时使用了两者。只需删除字符串开头的 f
。
试试
path = r'//div/div/div/span[contains(text(), "{}" )]'.format('test')