变量在括号内不起作用

Variable not working inside parenthesis

我有一个列表,我想使用该列表中的随机选项。

subjects = ['Beauty', 'Fashion', 'Hair', 'Nails', 'Skincare & Makeup', 'News']
random_item = random.choice(subjects)
print(random_item)

driver.find_element_by_xpath('//select[@name='input_4']/option[@value='random_item']').click()

我可以打印一个随机选择,但是 (random_item) 在 driver.find_element_by_xpath 命令中使用时不起作用。

我做错了什么或者我应该添加什么吗?

标识符不能与字符串文字相邻;那是无效的语法。

如果要将值插入字符串文字,可以使用 str.format:

driver.find_element_by_xpath('//select[@name={}]/option[@value={}]'.format(input_4, random_item)).click()