利用 Python 爬虫获取 URL 的方法:使用 requests 库使用 BeautifulSoup 库使用 urllib 库使用 Selenium 库
利用Python爬虫获取URL
在Python中获取URL有几种方法,具体取决于上下文的不同。
1. 使用requests库
requests库是一个HTTP库,可用于发送HTTP请求并获取网页的响应。要获取URL,可以使用以下方法:
立即学习“Python免费学习笔记(深入)”;
import requests url = "https://example.com/" response = requests.get(url) print(response.url) # 输出URL
2. 使用BeautifulSoup库
BeautifulSoup是一个HTML解析库,可以用来解析网页的内容。要获取URL,可以使用以下方法:
import requests from bs4 import BeautifulSoup url = "https://example.com/" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") for link in soup.find_all('a'): print(link.get('href')) # 输出每个链接的URL
3. 使用urllib库
urllib库是Python标准库中的一个HTTP库,可以用来发送HTTP请求并获取网页的响应。要获取URL,可以使用以下方法:
import urllib.request url = "https://example.com/" with urllib.request.urlopen(url) as response: print(response.geturl()) # 输出URL
4. 使用Selenium库
Selenium库是一个Web自动化库,可以用来控制浏览器并提取页面信息。要获取URL,可以使用以下方法:
from selenium import webdriver driver = webdriver.Firefox() driver.get("https://example.com/") print(driver.current_url) # 输出当前URL
以上就是python爬虫url怎么获得的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号