使用python修改当前的URL字符串查询

时间:2018-08-22 00:13:15

标签: python selenium-webdriver

我正在尝试在python中修改活动URL。我可以在现有代码中修改硬编码url的url,但是我想在apache服务器上修改页面的URL

例如,如果我在:

http://localhost/?foo=stackoverflow

我希望我的脚本将其修改为

http://localhost/?foo=Hello stackoverflow

我研究过的许多有关如何做到这一点的资料都使用了硬编码的URL。作为参考,这里是我正在做的代码,以及我正在谈论的修改。

 #!"C:/PythonPath"

import cgi
import datetime
import time

def htmlTop():
    print("""Content-type: text/html\n\n
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8"/>
            <title>My server template</title>
        </head>
        <body>""")
def htmlTail():
    print("""</body>
    </html>""")

if __name__ == "__main__":
    try:
        htmlTop()
        current_time = str(datetime.datetime.now())
        url = 'http://localhost/helloworld/?foo=bar'
        print(url)
        print("""<br></br>""")

        url_array = url.split('?')
        base_url = url_array[0] #'http://localhost/helloworld/?foo=bar'
        params = url_array[1] # query parameters 'foo'

        url_array2 = params.split("=") #['foo', 'bar']

        # print through all key values
        param_value_dict = {} # {'foo': 'bar'}
        for i, str in enumerate(url_array2):
            if i % 2 == 0:
                param_value_dict[str] = url_array2[i + 1]


        former_value = param_value_dict['foo'] # to store old value
        param_value_dict['foo'] = 'Hello '+former_value+'!  '+current_time

        # form the new url from the dictonary
        new_url = base_url + '?'
        for param_name, param_value in param_value_dict.items():
            new_url = new_url + param_name + "=" + param_value

        print(new_url.replace("%20", " "))
        htmlTail()
    except:
        cgi.print_exception()

1 个答案:

答案 0 :(得分:2)

我认为您正在使这项工作变得比需要做的还要困难。

import datetime
url = 'http://localhost/helloworld/?foo=bar'
url += ' ' + str(datetime.datetime.now())
print url.replace('=', '=Hello ').replace(' ', '%20')

结果

http://localhost/helloworld/?foo=Hello%20bar%202018-08-22 03:53:41.775949