将 Python 字符串与 javascript 值相结合

Combine Python String With Javascript Value

本文关键字:相结合 javascript Python 字符串      更新时间:2023-09-26
self.br.execute_script("document.getElementById('ctl00_phMainContent_KeywordForm_ControlPanel_txtKeywords').value = 'keywordurl';")

我在python中使用硒,我有以下执行Javascript的代码。keyworurl 的部分是一个大约 1300 行的 python 字符串列表。但是当我使用该代码时,它会写"关键字网址",而不是 python 中关键字网址所代表的内容......有什么想法吗?如果可以做" + 关键字网址 + " 什么的?

使用 Python 字符串格式:

for keywordurl in open("textfile.txt").readlines():
    self.br.execute_script( "document.getElementById('ctl00_phMainContent_KeywordForm_ControlPanel_txtKeywords').value = '%s';" % keywordurl )

%s -说明符将替换为%运算符后面的字符串。

更详细的信息:http://docs.python.org/2/library/stdtypes.html#string-formatting

可以在python:p中进行字符串添加。不过最好使用 str.format:

>>> print "Hello {}!".format("World")
"Hello World!"

由于听起来您有一个包含 1300 个字符串的列表,因此最好先在其上使用 list.join,将其转换为一个巨大的字符串。

>>> print "".join(["1", "2", "3"])
'123'