我有这样的xpath:
"//*[@id="comments_408947"]/div[2]/div[2]/div[2]"
comment_408947和整个xpath都必须用引号括起来。
我有一个数字408947作为字符串,需要将其添加到"comments_"之后
com_id = '408947'
query= f("//*[@id=comments_" + """%s""" + "]/div[2]/div[2]/div[2]", com_id)
但它不起作用。
使用三引号,它将为您解决问题,或者您需要转义内部"
,否则它将被解释为字符串端点。,
'''//*[@id="comments_408947"]/div[2]/div[2]/div[2]'''
"//*[@id="comments_408947"]/div[2]/div[2]/div[2]"
无效-您需要使用不同的引号来允许"
在字符内作为-或者您需要转义它们:
'''"//*[@id="comments_408947"]/div[2]/div[2]/div[2]"''' # works - uses ''' as delim
# too complex for string coloring here on SO but works:
""""//*[@id="comments_408947"]/div[2]/div[2]/div[2]"""" # works - uses """ as delim
"//*[@id="comments_408947"]/div[2]/div[2]/div[2]" # works - escapes "
'//*[@id="comments_408947"]/div[2]/div[2]/div[2]' # works - uses ' as delim
id插入也是如此-您可以使用字符串插值:
com_id = '408947'
query= f'''//*[@id="comments_{com_id}"]/div[2]/div[2]/div[2]''', com_id)