Dùng regex để tìm các thẻ <a> trong HTML. Lưu ý: Regex không parse HTML hoàn chỉnh, chỉ dùng cho quick extraction.
Ví dụ cơ bản (tìm ký tự < và >)
import re
rex = re.compile(r'[<>]')
html = "this is text1 hi this is text2"
print(rex.findall(html))
# ['<', '>', '<', '>']
Kết quả
['<', '>', '<', '>']
Pattern tốt hơn: Khớp toàn bộ thẻ <a>
# Khớp từ đến (non-greedy)
pattern = r']*>.*?'
html = "Link 1 text Link 2"
matches = re.findall(pattern, html, re.DOTALL)
print(matches)
# ["Link 1", "Link 2"]
Extract href và text
pattern = r']*href\s*=\s*["\']([^"\']+)["\'][^>]*>(.*?)'
for match in re.finditer(pattern, html, re.DOTALL | re.IGNORECASE):
url = match.group(1)
text = match.group(2)
print(f'URL: {url}, Text: {text}')
⚠️ Hạn chế của Regex cho HTML
- Không xử lý nested tags:
<a><a>...</a></a> - Không xử lý attribute chứa
>(trong quotes). - Không xử lý comment, script, style, CDATA.
- Case sensitivity, whitespace variation.
Cách khuyến nghị: BeautifulSoup
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
for a in soup.find_all('a', href=True):
print(f"URL: {a['href']}, Text: {a.get_text()}")
Chỉ dùng regex khi: HTML đơn giản, controlled format, one-time script, không cài được thư viện.