如何使用Python进行Web数据处理

时间:2007-10-09 14:25:27  来源:开发者在线  作者:

>>> x = [1,5,3,6,7,2,8,9,4]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7, 8, 9]

NB:感谢读者Jeremy提醒我sets是在Python中才引入的。如果你现在使用的是Python2.3,也可以通过字典完成同样的工作,下面的例子就是使用字典来完成上面的工作:

>>> x = ['set', 'contents', 'hello', 'world']

>>> y = dict.fromkeys(x)

>>> y

{'world': None, 'set': None, 'hello': None, 'contents': None}

>>> y['new item'] = None

>>> y

{'new item': None, 'world': None, 'set': None, 'hello': None, 'contents': None}

>>> y.keys()

['new item', 'world', 'set', 'hello', 'contents']

最终的程序代码

import sre, urllib2, sys, BaseHTTPServer

 

def parseAddress(input):

if input[:7] != "http://":

if input.find("://") != -1:

print "Error: Cannot retrive URL, address must be HTTP"

sys.exit(1)

else:

input = "http://" + input

return input

def retrieveWebPage(address):

try:

web_handle = urllib2.urlopen(address)

except urllib2.HTTPError, e:

error_desc = BaseHTTPServer.BaseHTTPRequestHandler.responses[e.code][0]

#print "Cannot retrieve URL: " + str(e.code) + ": " + error_desc

print "Cannot retrieve URL: HTTP Error Code", e.code

sys.exit(1)

except urllib2.URLError, e:

print "Cannot retrieve URL: " + e.reason[1]

sys.exit(1)

except:

print "Cannot retrieve URL: unknown error"

sys.exit(1)

return web_handle

if len(sys.argv) < 2:

print "Usage:"

print "%s url" % (sys.argv[0])

sys.exit(1)

match_set = set()

address = parseAddress(sys.argv[1])

website_handle = retrieveWebPage(address)

website_text = website_handle.read()

dir = website_handle.geturl().rsplit('/',1)[0]

if (dir == "http:/"):

dir = website_handle.geturl()

matches = sre.findall('<img .*src="(.*?)"', website_text)

for match in matches:

if match[:7] != "http://":

if match[0] == "/":

slash = ""

else:

slash = "/"

match_set.add(dir + slash + match)

else:

match_set.add(match)

match_set = list(match_set)

match_set.sort()

for item in match_set:

print item

做完这步之后,一个抓取Web页面图片地址的程序就完成了。这只是一个很小的例子,但是你以后开发的大部分程序都可以按照这样的模式进行。首先,检查用户输入。在这个例子中我们检查了参数的数目是否正确以及所给的网址是否正确。然后,收集处理数据。在这里我们下载了Web页面并提取其中的网址信息,并使用正规式表示。最后,组织数据,输出结果。

上一篇:Python快速入门

文章评论

共有 位CH网友发表了评论 查看完整内容