试试Beautifulsoup :
from BeautifulSoup import BeautifulSoup import urllib2 import re html_page = urllib2.urlopen("http://www.yourwebsite.com") soup = BeautifulSoup(html_page) for link in soup.findAll('a'): print link.get('href')
如果你只想要以http://开头的链接,你应该使用:
soup.findAll('a', attrs={'href': re.compile("^http://")})
您可以使用HTMLParser模块。
代码可能看起来像这样:
from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": print name, "=", value parser = MyHTMLParser() parser.feed(your_html_string)
注意: 在Python 3.0中,HTMLParser模块已经重命名为html.parser。 2to3工具将自