欢迎访问宙启技术站
智能推送

Python编程中获取当前URL的几种方法

发布时间:2023-12-16 08:45:56

在Python编程中,我们可以通过以下几种方法来获取当前URL:

1. 使用urllib.request库中的urlretrieve函数:

import urllib.request

url = urllib.request.urlopen('http://example.com')
current_url = url.geturl()
print(current_url)

2. 使用urllib.parse库中的urlparse函数:

from urllib.parse import urlparse

url = urlparse('http://example.com')
current_url = url.geturl()
print(current_url)

3. 使用requests库中的get方法:

import requests

response = requests.get('http://example.com')
current_url = response.url
print(current_url)

4. 使用BeautifulSoup库中的find方法:

import requests
from bs4 import BeautifulSoup

response = requests.get('http://example.com')
soup = BeautifulSoup(response.content, 'html.parser')
current_url = soup.find('a')['href']
print(current_url)

5. 使用webdriver库中的current_url属性:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://example.com')
current_url = driver.current_url
print(current_url)

这些方法每种都有不同的用法,可以根据实际需要选择适合的方法。以上是其中一些常用的方法示例,可以根据具体情况进行调整和扩展。