python获取网络数据_使用python访问网络上的数据

这两天看完了Course上面的:

使用 Python 访问网络数据

https://www.coursera.org/learn/python-network-data/

写了一些作业,完成了一些作业。做些学习笔记以做备忘。

1.正则表达式 --- 虽然后面的课程没有怎么用到这个知识点,但是这个技能还是蛮好的。

附上课程中列出来的主要正则表达式的用法:

Python Regular Expression Quick Guide^Matches the beginning of a line

$ Matches the end of the line

. Matches any character

\s Matches whitespace

\S Matches any non-whitespace character*Repeats a character zero or more times*?Repeats a character zero or more times

(non-greedy)+Repeats a character one or more times+?Repeats a character one or more times

(non-greedy)

[aeiou] Matches a single characterin the listed set[^XYZ] Matches a single character not in the listed set[a-z0-9] The setof characters can include a range

( Indicateswhere string extraction isto start

) Indicateswhere string extraction is to end

特别的以前没注意:From([0-9a-z]) 其实是取得符合整个规则的语句中()的部分。

并且 (.)并不表示任意字符而是只是.的意思。

附上作业编程:

import re

def sumText(name):

handle= open(name, 'r')

sum= 0

for line inhandle:

nums= re.findall('[0-9]+', line)if len(nums) >=1:for num innums:

sum+= int(num)returnsum

filedir= raw_input("imput fileName :")

sum1=sumText(filedir)

print sum1

2.使用python建立socket链接

介绍了下socket,一个用于和应用通讯的东西,每个网络应用都有对应的端口号,通过协议+主机名+端口就可以找到这个应用进行通讯了。

展示了使用telnet来获取http服务的方式。

telnet www.cnblogs.com 80GET http://www.cnblogs.com/webarn/p/6398989.html HTTP/1.0

不一定成功,觉得不是课程上面说的速度太慢的原因。

嗯附上自己知道比较简单的方式:

curl -XGET http://www.cnblogs.com/webarn/p/6398989.html

或者 使用python直接建立url链接,代码如下:

import socket

mysock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

mysock.connect(('data.pr4e.org', 80))

mysock.send('GET http://data.pr4e.org/intro-short.txt HTTP/1.0\n\n')whileTrue:

data= mysock.recv(512)if ( len(data) < 1) :breakprint data;

mysock.close()

再或者,使用浏览器的开发者工具也是一目了然的。

3.理解HTML并且进行解析

由于网页大部分都是html格式也就是超文本标记语言,是大部分网页展示的时候使用的语言,所以告诉了我们python里面也是有解析html 的包的:BeautifulSoup。

这个项目的链接如下:

https://www.crummy.com/software/BeautifulSoup/

使用详情可以查看它。

然后就是代码怎么使用了,还是自己作业的小小demo:

import urllibfrom BeautifulSoup import *url= raw_input('Enter -')

html=urllib.urlopen(url).read()

soup=BeautifulSoup(html)

sum= 0trs= soup('tr')for tr intrs:if tr.span isnot None:

num= int(tr.span.contents[0])

sum+=num

print sum

4.webService 和xml

介绍了xml,可扩展标记语言。主要用来传输和存储数据。可读性会比较强。很多webservice的通讯协议都是用xml来设计的。

其中有一个schme的概念,比如我们以前会写一些xsd文件来表示xml数据结构中的约束,比如字段是否可输还是必输,比如字段类型,这是一个约束,也是类似于协议的东西。

schema也会有很多的标准的。

xml解析用的是python内部的包:

xml.etree.ElementTree,将xml作为一个树状结构来解析了,要获取字段值要从根节点来数。

代码 如下:

import urllib

import xml.etree.ElementTreeasET

url= raw_input("Enter location:")

print'Retrieving', url

uh=urllib.urlopen(url)

data=uh.read()

print'\nRetrieved', len(data), 'characters'tree=ET.fromstring(data)

comments= tree.findall('.//comment')

sum= 0count=len(comments)

print'Count:', countfor comment incomments:

sum+= int(comment.find('count').text)

print'Sum:', sum

5.json,api

这节谈到了SOA,面向对象服务,大型的系统都会用到这个,感觉上是各个系统中都有一层中间层用于通讯,通讯所用的数据协议,格式都是统一的,这样可以互相通讯。当然里面还有服务发现等问题需要考虑。但是有了SOA的架构之后,各个不同的系统都可以通讯了。

api 课程中举了google map的api和twitter的api,各个应用可能都提供了api来进行调用,application program interface 就是和一个系统通讯的接口。api的格式比较简单,使用REST风格的调用。RESTFul风格感觉可以再写一篇文章了,可以看看他们直接的关系,但是我看到的api大都是网址+参数。就是这种 http://www.xxxx.com?para1=11&&param2=11这种,应该理解下来就是和前面说的协议+ 主机+ 端口+ 参数差不多了。

json介绍:json是一个简介的数据交换协议,只有一个版本,永远不会修改了,和xml比起来轻量很多,只有两个数据格式map,list。其他可以参看(json.org)(写这段chrome崩溃了3次,我也崩溃了。。。)然后就是loads才是解析string的,load是解析file的。

代码附上:

import json

import urllib

url= raw_input('Enter location:')

print'Retrieving', url

uh=urllib.urlopen(url)

data=uh.read()

print'Retrieved', len(data)

info=json.loads(data)

print'Count:', len(info['comments'])

sum= 0

for comment in info['comments']:

sum+= int(comment['count'])

print'Sum:', sum

api获取然后解析json的:

import urllib

import json

serviceurl= 'http://python-data.dr-chuck.net/geojson?'

whileTrue:

address= raw_input('Enter location:')if len(address) < 1:breakurl= serviceurl + urllib.urlencode({'sensor': 'false', 'address': address})

print'Retrieving', url

uh=urllib.urlopen(url)

data=uh.read()

print'Retrieved',len(data),'characters'

try: js =json.loads(str(data))

except: js=Noneif 'status' not in js or js['status'] != 'OK':

print'==== Failure To Retrieve ===='print datacontinueprint json.dumps(js, indent=4)

print'place_id:', js['results'][0]['place_id']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值