Dùng regex để extract URL từ attribute href trong thẻ <a>. Lưu ý: Regex không phải HTML parser hoàn chỉnh, chỉ dùng cho trường hợp đơn giản.
Ví dụ cơ bản
import re
html = 'Link'
# Pattern: href= + quote tùy chọn + capture URL + quote/closing
pattern = r'href=["\']?([^"\'>]+)'
match = re.search(pattern, html)
if match:
print(match.group(1)) # https://www.santa.com
Kết quả
https://www.santa.com
Pattern cải tiến (robust hơn)
# Xử lý: single/double quote, space quanh =, attribute khác trước/sau
pattern = r'href\s*=\s*["\']([^"\']+)["\']'
# Hoặc dùng non-greedy cho attribute value
pattern = r'href\s*=\s*["\'](.*?)["\']'
Extract TẤT CẢ links trong trang
html = '''
Site 1
Site 2
Site 3
'''
urls = re.findall(r'href\s*=\s*["\']?([^"\'>\s]+)', html)
print(urls)
# ['https://site1.com', 'https://site2.com', 'https://site3.com']
⚠️ Cảnh báo: Regex KHÔNG phải HTML Parser
Regex thất bại với: nested tags, comment, script/style content, malformed HTML, entity encoding.
Cách đúng: Dùng HTML Parser
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
urls = [a['href'] for a in soup.find_all('a', href=True)]
print(urls)
# ['https://site1.com', 'https://site2.com', 'https://site3.com']
Tóm tắt
- Regex đơn giản:
href=["\']?([^"\'>]+)cho trường hợp cơ bản. - Production: BeautifulSoup hoặc lxml.
- Regex chỉ dùng cho quick script, log parsing, HTML đơn giản/controlled.