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

7 投票
3 回答
10936 浏览
提问于 2025-04-16 23:34

目标网页是:

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>

一旦代码通过搜索关键词 "subclass 885
online
" 找到这个部分,它就应该打印出在第5个标签里的日期,也就是 "15 May 2011",如上所示。

这只是我自己用来监控我的移民申请进度的工具。

3 个回答

2

有一个叫做Beautiful Soup的库,可以帮你完成你想要的工作。你可以在这里找到它:http://www.crummy.com/software/BeautifulSoup/

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'
7

"美丽的汤!

美丽的汤!

傍晚的汤,

美丽,美丽的汤!"

--路易斯·卡罗尔, 爱丽丝梦游仙境

我觉得这正是他想表达的意思!

模拟海龟可能会这样做:

>>> 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

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

祝你申请顺利!

撰写回答