如何在Python中提取网页的某些部分

时间:2011-08-14 04:42:50

标签: python html string

目标网页: http://www.immi.gov.au/skilled/general-skilled-migration/estimated-allocation-times.htm

我要提取的部分:

  <tr>
  <td>Skilled &ndash; Independent (Residence) subclass 885<br />online</td>
  <td>N/A</td>
  <td>N/A</td>
  <td>N/A</td>
  <td>15 May 2011</td>
  <td>N/A</td>
  </tr>

代码通过搜索关键字“子类885在线”找到此部分后,应该打印第5个标记内的日期“ 5月15日2011年“如上所示。

这只是我自己的监视器,可以密切关注移民申请的进展情况。

3 个答案:

答案 0 :(得分:6)

您可能希望将此作为起点:

Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) 
[GCC 4.6.1 20110608 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2, re
>>> from BeautifulSoup import BeautifulSoup
>>> urllib2.urlopen('http://www.immi.gov.au/skilled/general-skilled-migration/estimated-allocation-times.htm')
<addinfourl at 139158380 whose fp = <socket._fileobject object at 0x84aa2ac>>
>>> html = _.read()
>>> soup = BeautifulSoup(html)
>>> soup.find(text = re.compile('\\bsubclass 885\\b')).parent.parent.find('td', text = re.compile(' [0-9]{4}$'))
u'15 May 2011'

答案 1 :(得分:6)

  

Beau--ootiful Soo--oop!

     

Beau--ootiful Soo--oop!

     

e-e-晚上的嘘声,

     

Beautiful, beauti--FUL SOUP!

- 刘易斯卡罗尔,Alice's Adventures in Wonderland

我认为这正是他的想法!

模拟海龟可能会做这样的事情:

>>> from BeautifulSoup import BeautifulSoup
>>> import urllib2
>>> url = 'http://www.immi.gov.au/skilled/general-skilled-migration/estimated-allocation-times.htm'
>>> page = urllib2.urlopen(url)
>>> soup = BeautifulSoup(page)
>>> for row in soup.html.body.findAll('tr'):
...     data = row.findAll('td')
...     if data and 'subclass 885online' in data[0].text:
...         print data[4].text
... 
15 May 2011

但是我不确定它会有所帮助,因为那个日期已经过去了!

祝你好运!

答案 2 :(得分:2)

有一个名为Beautiful Soup的图书馆可以完成你要求的工作。 http://www.crummy.com/software/BeautifulSoup/

相关问题