【问题标题】:Splinter: How to pass argument to execute_script?分裂:如何将参数传递给execute_script?
【发布时间】:2014-06-19 02:20:52
【问题描述】:

我需要在页面上执行一个 javascript 函数,方法是向它传递一个字符串数组。我想避免拨打browser.execute_script 的次数。

list_of_strings = ['a','b','c']

#js code runs through all the strings
result = browser.execute_script("function findTexts(textList){//code here}", list_of_strings)

【问题讨论】:

    标签: javascript python splinter


    【解决方案1】:

    将python列表转储到JSON并使用字符串格式

    import json
    
    json_array = json.dumps(list_of_strings)
    result = browser.execute_script("function findTexts(%s){//code here}" % json_array)
    

    这是它产生的 js 代码:

    >>> import json
    >>> list_of_strings = ['a','b','c']
    >>> json_array = json.dumps(list_of_strings)
    >>> "function findTexts(%s){//code here}" % json_array
    'function findTexts(["a", "b", "c"]){//code here}'
    

    【讨论】:

    • 在javascript代码中,我将如何遍历列表?如果列表中的项目数量不可预测怎么办?
    • @KJW 只使用基本的 javascript 循环,请参阅 stackoverflow.com/questions/3010840/…
    • 我最终这样做了browser.evaluate_script("findTexts(%s);function findTexts(list){//do something with list array}"); 结果evaluate_script 返回了结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-03
    • 2020-10-09
    • 2012-12-21
    • 2012-01-07
    • 2014-05-03
    • 2015-06-26
    相关资源
    最近更新 更多