使用Python编写一个函数来获取当前网页的URL地址
发布时间:2023-12-16 08:47:50
要获取当前网页的URL地址,可以使用Python的webbrowser模块。webbrowser模块提供了打开浏览器和控制浏览器的功能。
首先,导入webbrowser模块:
import webbrowser
然后,使用webbrowser模块的get()函数来获取当前网页的URL地址:
url = webbrowser.get().open('http://example.com')
上述代码会打开一个新的浏览器窗口,并显示http://example.com网页,然后将该网页的URL地址保存在变量url中。
下面是一个完整的示例代码:
import webbrowser
def get_current_url():
url = webbrowser.get().open('http://example.com')
return url
current_url = get_current_url()
print("Current URL: " + current_url)
运行上述代码,你会得到类似以下输出:
Current URL: http://example.com
这样就成功获取了当前网页的URL地址。注意,这个方法只能获取打开新的浏览器窗口的URL地址。
如果要获取正在运行的Python脚本的URL地址,可以使用urllib模块:
from urllib.parse import urlparse
def get_current_url():
url = urlparse('http://example.com')
return url.geturl()
current_url = get_current_url()
print("Current URL: " + current_url)
在上述代码中,使用了urllib模块的parse子模块中的urlparse()函数来解析URL地址,并使用geturl()方法获取完整的URL地址。
使用上述代码,你可以获取到当前网页的URL地址,并对其进行进一步的操作和处理。
