
python如何获取网页url
用户关注问题
如何在Python中获取当前网页的URL地址?
如果我正在用Python编写爬虫或自动化脚本,怎样获取当前网页的URL地址?
用Python获取当前网页URL的方法
可以使用Selenium库,通过driver.current_url属性获取当前网页的URL。示例如下:
from selenium import webdriver
# 创建浏览器驱动
driver = webdriver.Chrome()
# 打开网页
driver.get('https://www.example.com')
# 获取当前网页的URL
current_url = driver.current_url
print(current_url)
# 关闭浏览器
driver.quit()
使用requests库时,如何获取请求后的网页URL?
用requests库发送请求后,如果网页发生重定向,怎么获得最终网页的URL?
requests库获取响应页面URL的方式
当使用requests库发起请求时,可以通过response.url属性获得最终返回页面的URL,尤其是在发生重定向时。如下示例:
import requests
response = requests.get('http://github.com')
print(response.url) # 输出可能为'https://github.com/'
如何从HTML源码中提取页面中的链接URL?
用Python解析网页源代码时,怎样提取网页中所有的链接地址?
用BeautifulSoup提取网页所有超链接
借助BeautifulSoup库解析HTML文档,可以找到所有标签并获取其href属性,示例如下:
from bs4 import BeautifulSoup
html_doc = '''<html><body><a href='https://example.com'>example</a></body></html>'''
soup = BeautifulSoup(html_doc, 'html.parser')
links = [a['href'] for a in soup.find_all('a', href=True)]
print(links) # 输出 ['https://example.com']