从Python中读取网页内容的问题

4

我正在尝试从web上读取一个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文档时遇到了一些困难。请看这个网页

1
你遇到了什么困难? - Sergio Tulentsev
我尝试使用“findall”方法,但不确定应该使用哪些参数? - tush1r
它失败了,显示以下内容...Traceback (most recent call last): File "c:\Work\Learn\Python\Web.py", line 27, in <module> main() File "c:\Work\Learn\Python\Web.py", line 23, in main Connect2Web() File "c:\Work\Learn\Python\Web.py", line 18, in Connect2Web matches = re.findall(["SILVER"],web_pg) File "c:\Program Files\Python27\lib\re.py", line 177, in findall return _compile(pattern, flags).findall(string) File "c:\Program Files\Python27\lib\re.py", line 231, in _compile p = _cache.get(cachekey) TypeError: unhashable type: 'list' - tush1r
1
请编辑问题,并在那里添加信息(如果可能的话,请以漂亮的格式呈现)。 - Rik Poggi
我调整了您的缩进(不确定是否可以)。我不是许可证专家,但我认为通过在这里发布您的代码,它将有效地发布在CC-Wiki下,因此您的版权声明无效。重新表述一下:如果您发布的代码受版权保护,则可能存在许可侵权问题。 - Rik Poggi
显示剩余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_installpip 程序进行安装。

谢谢Keith,但是我无法编译上述代码,我正在使用Python 2.7.2,似乎无法获取“html5lib”模块。 请问您使用的是哪个版本的Python? - tush1r
@tush1r 你需要安装它。确保你有 easy_install。如果没有,请谷歌搜索 ez_setup - Marcin
哦,我忘了那是第三方模块。请参考html5lib网站easy_installpip程序应该能够安装它。 - Keith
似乎在 d.getElementsByTagName("tr") 中有一些打错字了 - "d" 未定义。 - Oleg Neumyvakin
也许他的意思是“dom”,而不是“d”? - Kirk Boyer

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


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'

祝你好运。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接