Đầu tiên thiết lập một tài liệu thử nghiệm và mở ra các phân tích cú pháp với BeautifulSoup:
>>> from BeautifulSoup import BeautifulSoup
>>> doc = '<html><body><div><a href="something">yep</a></div><div><a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a></div><a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a></body></html>'
>>> soup = BeautifulSoup(doc)
>>> print soup.prettify()
<html>
<body>
<div>
<a href="something">
yep
</a>
</div>
<div>
<a href="http://www.nhl.com/ice/boxscore.htm?id=3">
somelink
</a>
</div>
<a href="http://www.nhl.com/ice/boxscore.htm?id=7">
another
</a>
</body>
</html>
Tiếp theo, chúng ta có thể tìm kiếm tất cả <a>
thẻ với một href
thuộc tính bắt đầu với http://www.nhl.com/ice/boxscore.htm?id=
. Bạn có thể sử dụng một biểu thức chính quy cho nó:
>>> import re
>>> soup.findAll('a', href=re.compile('^http://www.nhl.com/ice/boxscore.htm\?id='))
[<a href="http://www.nhl.com/ice/boxscore.htm?id=3">somelink</a>, <a href="http://www.nhl.com/ice/boxscore.htm?id=7">another</a>]
Wow cảm ơn. Tôi đoán tài liệu của Beautifulsoup giả định sự lưu loát trong regex. Cảm ơn bạn đã cho tôi biết rằng –
@JenScott Nếu điều này đã trả lời câu hỏi của bạn, bạn nên chấp nhận câu hỏi đó. – serk
Tốt nhưng nếu tên thuộc tính của bạn được gọi là "lớp" thì sao? – Wajih