• 使用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 character in the listed set
    [^XYZ]   Matches a single character not in the listed set
    [a-z0-9] The set of characters can include a range
    (        Indicates where string extraction is to start
    )        Indicates where string extraction is to end

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

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

    附上作业编程:

    import re
    
    def sumText(name):
            handle = open(name, 'r')
            sum = 0
            for line in handle:
                    nums = re.findall('[0-9]+', line)
                    if len(nums) >=1:
                            for num in nums:
                                    sum += int(num)
            return sum
    
    filedir = raw_input("imput fileName :")
    sum1 = sumText(filedir)
    print sum1

    2.使用python建立socket链接

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

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

    telnet www.cnblogs.com 80
     GET 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
    
    ')
    
    while True:
        data = mysock.recv(512)
        if ( len(data) < 1 ) :
            break
        print data;
    
    mysock.close()

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

    3.理解HTML并且进行解析

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

    这个项目的链接如下:

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

    使用详情可以查看它。

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

    import urllib
    from BeautifulSoup import *
    
    url = raw_input('Enter - ')
    html = urllib.urlopen(url).read()
    
    soup = BeautifulSoup(html)
    
    sum = 0
    trs = soup('tr')
    for tr in trs:
            if tr.span is not 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.ElementTree as ET
    
    url = raw_input("Enter location:")
    print 'Retrieving', url
    uh = urllib.urlopen(url)
    data = uh.read()
    print '
    Retrieved ', len(data), ' characters'
    tree = ET.fromstring(data)
    
    comments = tree.findall('.//comment')
    sum = 0
    count = len(comments)
    print 'Count:', count
    for comment in comments:
            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?'
    
    while True:
            address = raw_input('Enter location:')
    
            if len(address) < 1 :
                    break
    
            url = 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 = None
            if 'status' not in js or js['status'] != 'OK':
                    print '==== Failure To Retrieve ===='
                    print data
                    continue
    
            print json.dumps(js, indent=4)
    
            print 'place_id:', js['results'][0]['place_id']
  • 相关阅读:
    ansible 使用密码登录
    shell脚本报错:-bash: xxx: /bin/bash^M: bad interpreter: No such file or directory
    配置永久生效(登陆shell和非登陆shell)、I/O重定向、Here Docunmet 此处文档、管道、tee
    Navicat for PostgreSQL 序列详解
    flask第十五篇——Response
    Centos防火墙及SELINUX关闭
    linux查看网卡信息的几种方法(命令)
    Python之在函数中调用import语句
    python基础_格式化输出(%用法和format用法)
    Python中怎样简单地用一行写if-then语句?
  • 原文地址:https://www.cnblogs.com/edenpans/p/6403307.html
Copyright © 2020-2023  润新知