4

我正在尝试从网络上的 python 模块中读取一些数据。

我设法阅读,但是在解析这些数据和获取所需信息时遇到了一些困难。

我的代码如下。任何帮助表示赞赏。

#!/usr/bin/python2.7 -tt

import urllib
import urllib2

def Connect2Web():
  aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp");
  web_pg = aResp.read();

  print web_pg

#Define a main() function that prints a litte greeting
def main():
  Connect2Web()

# This is the standard boilerplate that calls the maun function.
if __name__ == '__main__':
    main()

当我打印此网页时,我会打印整个网页。

我想从中提取一些信息(例如"SILVER PASSBOOK ACCOUNT"并从中获取费率),我在解析这个 html 文档时遇到了一些困难。

4

3 回答 3

9

不推荐使用 RE 来匹配 XML/HTML。但是,它有时可以工作。最好使用 HTML 解析器和 DOM API。这是一个例子:

import html5lib
import urllib2

aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp")
t = aResp.read()
dom = html5lib.parse(t, treebuilder="dom")
trlist = dom.getElementsByTagName("tr")
print trlist[-3].childNodes[1].firstChild.childNodes[0].nodeValue

您可以迭代trlist以找到您感兴趣的数据。

从评论中添加: html5lib是第三方模块。请参阅html5lib 站点easy_installorpip程序应该能够安装它。

于 2012-04-08T09:39:12.207 回答
4

可以使用正则表达式来获取所需的数据:

import urllib
import urllib2
import re

def Connect2Web():
  aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp");
  web_pg = aResp.read();

  pattern = "<td><b>SILVER PASSBOOK ACCOUNT</b></td>" + "<td>(.*)</td>" * 4
  m = re.search(pattern, web_pg)
  if m:
    print "SILVER PASSBOOK ACCOUNT:"
    print "\tCurrency:", m.group(1)
    print "\tUnit:", m.group(2)
    print "\tBank Sells:", m.group(3)
    print "\tBank Buys:", m.group(4)
  else:
    print "Nothing found"

re.compile如果您在循环中进行匹配,请不要忘记模式。

于 2012-04-08T09:05:02.360 回答
1

你也可以试试Grablib。和/或您可以使用 XPath(带/不带 Grab)。以后可能对你有用,这里有一些例子:

g = Grab()
g.go(address)

user_div = g.xpath('//*/div[@class="user_profile"]') # main <div> for parse
country = user_div.find('*/*/a[@class="country-name"]')
region  = user_div.find('*/*/a[@class="region"]')    # look for <a class="region">
city    = user_div.find('*/*/a[@class="city"]')

friends = [ i.text_content() for i in user_div.findall('dl[@class="friends_list"]/dd/ul/li/a[@rel="friend"]') ]

# and another ability, i.e. you have 2 tags: 
# <tr> <td>Text to grab</td> <td>if only that tag contains this text</td> </tr>

val = user_div.xpath(u"dl/dt[contains(text(),'%s')]/../dd/text()" % 'if only that tag contains this text')
# print val[0] <- will contain 'Text to grab'

祝你好运。

于 2012-04-08T10:40:13.647 回答