Don't use regex to parse html. Use a real parser.
I suggest using the lxml.html
parser. lxml
supports xpath, which is a very powerful way of querying structured documents. There's a ready-to-use make_links_absolute()
method that does what you ask. It's also very fast.
As an example, in this question's page HTML source code (the one you're reading now) there's this part:
<li><a id="nav-tags" href="/tags">Tags</a></li>
The xpath expression //a[@id='nav-tags']/@href
means: "Get me the href
attribute of all <a>
tags with id
attribute equal to nav-tags
". Let's use it:
from lxml import html
url = 'http://stackoverflow.com/questions/3423822/python-url-regexp'
doc = html.parse(url).getroot()
doc.make_links_absolute()
links = doc.xpath("//a[@id='nav-tags']/@href")
print links
The result:
['http://stackoverflow.com/tags']