嗯,首先,該鏈接或表格行沒有唯一標識符,因此將無法通過cssselect
獲取該標識符,如果您不知道URL的哪一部分或標題將是。
假設您要匹配節號2.1
。查看該頁面,節號始終位於連續的第一個單元格中。一旦找到正確的單元格,就可以遍歷到它的第二個兄弟節點,它應該包含鏈接,然後從鏈接中獲取URL。
>>> import urllib2
>>> from StringIO import StringIO
>>> from lxml import etree
>>> url = "http://www.bnm.gov.my/index.php?ch=109&pg=294&mth=3&yr=2012&eId=box1"
>>> ufile = urllib2.urlopen(url)
>>> root = etree.parse(ufile, etree.HTMLParser())
>>> for e in root.getiterator('tr'):
... fc = e[0] # first child
... if fc.tag == 'td' and fc.text == '2.1':
... link = fc.getnext().getnext()[0] # first child of 2nd sibling
... print link.attrib["href"]
...
files/publication/msb/2012/3/xls/2.1.xls