Hi All -
I'm looking to use Python and xml.dom.minidom to get a list of links within a particular <table>
specified by the table id. Based on some excellent advice, I'm trying to use the DOM instead of pattern matching.
import urllib
import xml.dom.minidom
url = 'http://www.batstrading.com/market_data/shortsales'
page = xml.dom.minidom.parse(urllib.urlopen(url))
I can get all the links by the tag name page.getElementsByTagName('a')
, but I cannot limit the links returned by those only contained within the table with ID "monthly-short-sale".
Using getElementById
returns None.
Is this because the "monthly-short-sale" ID is not defined within the DTD? If so, what would be the best way to extract this information?
Here is the code that I'm currently using, which works, but sins against god:
import urllib
import xml.dom.minidom
import datetime
url = 'http://www.batstrading.com/market_data/shortsales'
def getDownloadLink(alink, prefix = 'BATSsh'):
"""return (datetime.date, link) for the provided link if the link
target starts with the data file prefix"""
n = len(prefix)
href = alink.getAttribute('href')
if href.startswith(prefix) and (len(href) == 25):
year = int(href[n:n+4])
month = int(href[n+4:n+6])
day = int(href[n+6:n+8])
date = datetime.date(year, month, day)
return (date, url + '/' + href)
page = xml.dom.minidom.parse(urllib.urlopen(url))
link = (getDownloadLink(a) for a in page.getElementsByTagName('a'))
link = dict(i for i in link if i is not None)