python 如何获取链接

python 如何获取链接

作者:Joshua Lee发布时间:2026-01-05阅读时长:0 分钟阅读次数:45

用户关注问题

Q
如何使用 Python 提取网页中的所有链接?

我想用 Python 从一个网页的 HTML 内容中获取所有的超链接(URL),应该使用哪些库和方法?

A

使用 BeautifulSoup 库提取网页链接

可以使用 Python 的 requests 库请求网页内容,然后用 BeautifulSoup 库解析 HTML。通过使用 find_all('a') 方法找到所有的标签,再通过属性 href 获取链接。例如:

import requests
from bs4 import BeautifulSoup

response = requests.get('http://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
links = [a['href'] for a in soup.find_all('a', href=True)]
print(links)