跳转至

Blog

Python中的urllib2库的使用

今天研究了下urllib2这个库的使用,才发现以前有很多不明白的东西,现在写下来也做个记录

最基础的应用

1
2
3
import urllib2
url = r'http://www.baidu.com'
html = urllib2.urlopen(url).read()

客户端与服务器端通过request与response来沟通,客户端先向服务端发送request,然后接收服务端返回的response

urllib2提供了request的类,可以让用户在发送请求前先构造一个request的对象,然后通过urllib2.urlopen方法来发送请求

1
2
3
4
import urllib2
url = r'http://www.baidu.com'
req = urllib2.Request(url)
html = urllib2.urlopen(req).read()

python解析json

相对于python解析XML来说,我还是比较喜欢json的格式返回,现在一般的api返回都会有json与XML格式的选择,json的解析起来个人觉得相对简单些

先看一个简单的豆瓣的图书查询的api返回

Python解析XML文档

解析XML主要用到pytohn自带的XML库,其次还是lxml库

XML结构

先以一个相对简单但功能比较全的XML文档为例

<?xml version='1.0' encoding='utf-8'?>
<feed xmlns='http://www.w3.org/2005/Atom' xml:lang='en'>
  <title>dive into mark</title>
  <subtitle>currently between addictions</subtitle>
  <id>tag:diveintomark.org,2001-07-29:/</id>
  <updated>2009-03-27T21:56:07Z</updated>
  <link rel='alternate' type='text/html' href='http://diveintomark.org/'/>
  <entry>
    <author>
      <name>Mark</name>
      <uri>http://diveintomark.org/</uri>
    </author>
    <title>Dive into history, 2009 edition</title>
    <link rel='alternate' type='text/html'
      href='http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition'/>
    <id>tag:diveintomark.org,2009-03-27:/archives/20090327172042</id>
    <updated>2009-03-27T21:56:07Z</updated>
    <published>2009-03-27T17:20:42Z</published>
    <category scheme='http://diveintomark.org' term='diveintopython'/>
    <category scheme='http://diveintomark.org' term='docbook'/>
    <category scheme='http://diveintomark.org' term='html'/>
    <summary type='html'>Putting an entire chapter on one page sounds
      bloated, but consider this &mdash; my longest chapter so far
      would be 75 printed pages, and it loads in under 5 seconds&hellip;
      On dialup.</summary>
  </entry>
  <entry>
    <author>
      <name>Mark</name>
      <uri>http://diveintomark.org/</uri>
    </author>
    <title>Accessibility is a harsh mistress</title>
    <link rel='alternate' type='text/html'
      href='http://diveintomark.org/archives/2009/03/21/accessibility-is-a-harsh-mistress'/>
    <id>tag:diveintomark.org,2009-03-21:/archives/20090321200928</id>
    <updated>2009-03-22T01:05:37Z</updated>
    <published>2009-03-21T20:09:28Z</published>
    <category scheme='http://diveintomark.org' term='accessibility'/>
    <summary type='html'>The accessibility orthodoxy does not permit people to
      question the value of features that are rarely useful and rarely used.</summary>
  </entry>
  <entry>
    <author>
      <name>Mark</name>
    </author>
    <title>A gentle introduction to video encoding, part 1: container formats</title>
    <link rel='alternate' type='text/html'
      href='http://diveintomark.org/archives/2008/12/18/give-part-1-container-formats'/>
    <id>tag:diveintomark.org,2008-12-18:/archives/20081218155422</id>
    <updated>2009-01-11T19:39:22Z</updated>
    <published>2008-12-18T15:54:22Z</published>
    <category scheme='http://diveintomark.org' term='asf'/>
    <category scheme='http://diveintomark.org' term='avi'/>
    <category scheme='http://diveintomark.org' term='encoding'/>
    <category scheme='http://diveintomark.org' term='flv'/>
    <category scheme='http://diveintomark.org' term='GIVE'/>
    <category scheme='http://diveintomark.org' term='mp4'/>
    <category scheme='http://diveintomark.org' term='ogg'/>
    <category scheme='http://diveintomark.org' term='video'/>
    <summary type='html'>These notes will eventually become part of a
      tech talk on video encoding.</summary>
  </entry>
</feed>

先简单的看一下这个XML的结构

python发邮件是件很简单的事情

利用python的smtplib,发邮件将是一件非常简单的事情,下文以用163邮箱来发邮件为例,说明smtplib的应用

#coding:utf-8
import smtplib

def sendMail(mail_to):
    mail_server = 'smtp.163.com'
    mail_port = '25'
    username = 'soar_1987@163.com'
    password = 'XXXXXXXX'
    mail_title = 'python Test'
    mail_content = 'This is a test from python for sending email'
    if type(mail_to) == str:#之所以要有这样的判断是为了收件人是多个人或者传入的的收件人列表是以list的方式
        mail_list = mail_to.split(';') #将str类型的数据转换为list
    elif type(mail_to) == list:
        mail_list = mail_to
    else:
        print "你输入的收件人格式有误"

    try:
        handle = smtplib.SMTP(mail_server,mail_port)
        handle.login(username,password)
        msg = "From:%srn To:%srnContent-Type: text/html;charset=gb2312rnSubject:%srnrn %s"%("杨彦星",";".join(mail_list),mail_title,mail_content) #这里的msg其实就是一种固定的格式,From:To:Subject
        handle.sendmail(username,mail_list,msg)
        print "Send email sucess"
    except Exception,e:
        print "Send email failed because %s" % e

if __name__ =="__main__":
    sendMail('yanxingyang@gmail.com')

可爱的python中的一个与递归相关的小问题

可爱的python一书中有一个练习题,是在一个目录中查找特定扩展名的文件,并且读取里面的内容,然后用户输入一个关键词,在这些文件中进行搜索,如果找到后就把这一行内容打印出来,他提出的问题是如果里面还有目录,目录里面还有更深的目录,解决这个问题,我想到的只能是递归。。。

#coding:utf-8
import os,sys

def cdGrep(keyword,filepath):
    filelist = os.listdir(filepath)

    for cdc in filelist:
        if os.path.isdir(cdc):
            filepath2 = os.path.join(filepath,cdc)
            cdGrep(keyword,filepath2)

        elif '.txt' in cdc:
#            print filepath+cdc
            f = open(filepath+''+ cdc)
            for line in f.readlines():
                linelower = line.lower()
                if keyword in linelower:

                    print '您查找的关键词在%s中找到'% (filepath+''+cdc)
                    print line
                f.close()

if __name__ == '__main__':
    keword = raw_input('请输入想要查询的关键字')
    pw = os.getcwd()
    cdGrep(keword,pw)

通过一个python小脚本来下载最新的360杀毒安装程序

小脚本很简单,主要是练习一下正则匹配,与简单的urllib库的应用

#coding: utf8
import urllib,re
import os

def getLastinstall():

    page = urllib.urlopen(r'http://sd.360.cn/download_center.html')
    html = page.read()
    page.close()
    rematch = r'http://down.360.cn/360sd/360sd_se_(.*?)exe'
    replusmatch = r'http://down.360.cn/360sd/360sd_plus_(.*?)exe'
    stdname = '360sd_'+(str(re.compile(rematch).findall(html)[0]))+'exe'
    downurlstd = r'http://down.360.cn/360sd/360sd_'+(str(re.compile(rematch).findall(html)[0]))+'exe'
    powname = '360sd_plus_'+(str(re.compile(replusmatch).findall(html)[0]))+'exe'
    downurlpow = r'http://down.360.cn/360sd/360sd_plus_'+(str(re.compile(replusmatch).findall(html)[0]))+'exe'
    localpath = os.getcwd()+r'/installpack'
    if not (os.path.isfile(stdname) and os.path.isfile(powname)):
        if not os.path.isdir('installpack'):
            os.makedirs('installpack')
        urllib.urlretrieve(downurlstd,localpath+'/'+stdname)
        urllib.urlretrieve(downurlpow,localpath+'/'+powname)
    else:
        print '目录中已经是线上最新版杀毒安装程序'

if __name__ =='__main__':
    getLastinstall()

python中的OOP

直接上代码,已经在后面有注释了

#coding:utf8

name = 'yangyanxing'
class Test():
    class kevin():
        var1 = '我是内部类'

    name = 'kvein'
    gae = '26'

    def fun1(self):
        print self.name
        print '我是公共方法'
        self.__fun2() #可以通过公有就去来调用私有方法,在调用的过程中可以进行更改

    def __fun2(self):
        print '我是私有方法'

    @classmethod
    def fun3(self): #可以不通过实例来访问这个类方法
        print '#'*40
        print self.name
        print '我是类方法'

    @staticmethod #静态方法,也是可以不通过实例对象就可以访问的方法但是在定义的时候不用加self
    def fun4():
        print Test.name
        print name #这里的name是全局变量
        Test.fun3()
        print '我是静态方法'

print Test.name #公有属性可以直接方法,不用实例化对象
yang = Test() #实例化一个类
interyang = Test.kevin() #实例化一个内部类
yang.fun1() #方法类里面的公共属性
print interyang.var1 # 访问内部类里的属性
Test.fun3()#访问类方法
Test.fun4()
#coding:utf8

class Test():
    var1 = '类的公有属性'
    __var2 = '类的私有属性'

    def fun(self):
        self.var2 = '对象的公有属性' # 这里定义了一个对象的公有属性
        self.__var3 = '对象的私有属性'# 这里定义了一个对象的私有属性
        var4 = '函数的局部变量' #这里定义了一个函数的局部变量,这里面的var4只有在函数内部使用

kevin = Test() #实例了一个对象
yang = Test() #又实例了另外一个对象
print kevin.var1
##print kevin.__var2 #这里将无法访问
kevin.fun()
print kevin.var2 #在没有调用fun函数之前是没有var2的
##print kevin.__var3 对象的私有属性是无法调用的
##print yang.var2 #这里因为没有调用yang的fun方法,所以还是无法访问yang里的var2

(转)抛砖引玉 正则表达式完成电话号码的匹配

原来地址:http://www.diveintopython.net/regular_expressions/phone_numbers.html

迄今为止,你主要是匹配整个模式,不论是匹配上,还是没有匹配上。但是正则表达式还有比这更为强大的功能。当一个模式确实 匹配上时,你可以获取模式中特定的片断,你可以发现具体匹配的位置。 这个例子来源于我遇到的另一个现实世界的问题,也是在以前的工作中遇到的。问题是:解析一个美国电话号码。客户要能 (在一个单一的区域中) 输入任何数字,然后存储区号、干线号、电话号和一个可选的独立的分机号到公司数据库里。为此,我通过网络找了很多正则表达式的例子,但是没有一个能够完全满足我的要求。 这里列举了我必须能够接受的电话号码:  800-555-1212  800 555 1212  800.555.1212  (800) 555-1212  1-800-555-1212  800-555-1212-1234  800-555-1212x1234  800-555-1212 ext. 1234  work 1-(800) 555.1212 #1234 格式可真够多的!我需要知道区号是 800,干线号是 555,电话号的其他数字为 1212。对于那些有分机号的,我需要知道分机号为 1234。 让我们完成电话号码解析这个工作,这个例子展示第一步。 例 7.10. 发现数字

phonePattern = re.compile(r'^(d{3})-(d{3})-(d{4})$') (1) phonePattern.search('800-555-1212').groups() (2)