從網頁抓取所有 `` 連結是爬蟲基礎操作,本文示範使用 urllib 獲取頁面、BeautifulSoup 解析提取連結、處理相對/絕對 URL、去重與過濾。
import urllib.request
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
def extract_links(url):
try:
with urllib.request.urlopen(url, timeout=10) as resp:
html = resp.read()
except Exception as e:
print(f"Fetch failed: {e}")
return []
soup = BeautifulSoup(html, 'html.parser')
base_url = resp.geturl() # 取得最終 URL (處理重導向)
links = set()
for a in soup.find_all('a', href=True):
href = a['href'].strip()
if not href or href.startswith(('javascript:', 'mailto:', 'tel:', '#')):
continue
# 轉為絕對 URL
abs_url = urljoin(base_url, href)
# 可選:只保留同域名
if urlparse(abs_url).netloc == urlparse(base_url).netloc:
links.add(abs_url)
return sorted(links)
if __name__ == '__main__':
target = 'https://example.com'
for link in extract_links(target):
print(link)
urllib.request.urlopen 或 requests.get。BeautifulSoup(html, 'html.parser') (標準庫) 或 'lxml' (需安裝,更快)。soup.find_all('a', href=True) 只選有 href 屬性的標籤。urljoin(base, href) 處理相對路徑 (如 /about, ../page)。set()。for a in soup.find_all('a'):
print({
'href': a.get('href'),
'text': a.get_text(strip=True),
'title': a.get('title'),
'rel': a.get('rel'),
'target': a.get('target'),
'class': a.get('class')
})
aiohttp + lxml 異步解析。lxml.html 的 iterlinks() 避免建構完整 DOM 樹。robots.txt 與網站服務條款。User-Agent、請求間隔、並發數。