One simple way to parse HTML is to use regular expressions to repeatedly search and extract for substrings that match a particular pattern.
Here is a simple web page:
<h1>The First Page</h1><p>If you like, you can switch to the<a href="http://www.dr-chuck.com/page2.htm">Second Page</a>.</p>
We can construct a well-formed regular expression to match and extract the link values from the above text as follows:
Our regular expression looks for strings that start with “href=”http://” followed by one or more characters “.+?” followed by another double quote. The question mark added to the “.+?” indicates that the match is to be done in a “non-greedy” fashion instead of a “greedy” fashion. A non-greedy match tries to find the smallest possible matching string and a greedy match tries to find the largest possible matching string.
We need to add parentheses to our regular expression to indicate which part of our matched string we would like to extract and produce the following program:
import urllib import re url = raw_input('Enter - ')html = urllib.urlopen(url).read()links = re.findall('href="(http://.*?)"', html)for link in links: print link
The findall regular expression method will give us a list of all of the strings that match our regular expression, returning only the link text between the double quotes.
When we run the program, we get the following output:
python urlregex.pyEnter - http://www.dr-chuck.com/page1.htmhttp://www.dr-chuck.com/page2.htm python urlregex.pyEnter - http://www.py4inf.com/book.htmhttp://www.greenteapress.com/thinkpython/thinkpython.htmlhttp://allendowney.com/http://www.py4inf.com/codehttp://www.lib.umich.edu/espresso-book-machinehttp://www.py4inf.com/py4inf-slides.zip
Regular expressions work very nice when your HTML is well-formatted and predictable. But since there is a lot of “broken” HTML pages out there, you might find that a solution only using regular expressions might either miss some valid links or end up with bad data.
This can be solved by using a robust HTML parsing library.