pycurl实例详解

Pycurl是Python的libcurl接口。liburl是客户端的URL传输库,它支持FTP,FTPS,HTTP,HTTPS,TELNET,LDAP等诸多协议,同时支持HTTP认证,代理,FTP上传,cookies等。

功能:

  c = pycurl.Curl() #创建一个curl对象 c.setopt(pycurl.CONNECTTIMEOUT, 5) #连接的等待时间,设置为0则不等待 c.setopt(pycurl.TIMEOUT, 5) #请求超时时间 c.setopt(pycurl.NOPROGRESS, 0) #是否屏蔽下载进度条,非0则屏蔽 c.setopt(pycurl.MAXREDIRS, 5) #指定HTTP重定向的最大数 c.setopt(pycurl.FORBID_REUSE, 1) #完成交互后强制断开连接,不重用 c.setopt(pycurl.FRESH_CONNECT,1) #强制获取新的连接,即替代缓存中的连接 c.setopt(pycurl.DNS_CACHE_TIMEOUT,60) #设置保存DNS信息的时间,默认为120秒 c.setopt(pycurl.URL,"http://www.baidu.com") #指定请求的URL c.setopt(pycurl.USERAGENT,"Mozilla/5.2 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50324)") #配置请求HTTP头的User-Agent c.setopt(pycurl.HEADERFUNCTION, getheader) #将返回的HTTP HEADER定向到回调函数getheader c.setopt(pycurl.WRITEFUNCTION, getbody) #将返回的内容定向到回调函数getbody c.setopt(pycurl.WRITEHEADER, fileobj) #将返回的HTTP HEADER定向到fileobj文件对象 c.setopt(pycurl.WRITEDATA, fileobj) #将返回的HTML内容定向到fileobj文件对象 c.getinfo(pycurl.HTTP_CODE) #返回的HTTP状态码 c.getinfo(pycurl.TOTAL_TIME) #传输结束所消耗的总时间 c.getinfo(pycurl.NAMELOOKUP_TIME) #DNS解析所消耗的时间 c.getinfo(pycurl.CONNECT_TIME) #建立连接所消耗的时间 c.getinfo(pycurl.PRETRANSFER_TIME) #从建立连接到准备传输所消耗的时间 c.getinfo(pycurl.STARTTRANSFER_TIME) #从建立连接到传输开始消耗的时间 c.getinfo(pycurl.REDIRECT_TIME) #重定向所消耗的时间 c.getinfo(pycurl.SIZE_UPLOAD) #上传数据包大小 c.getinfo(pycurl.SIZE_DOWNLOAD) #下载数据包大小 c.getinfo(pycurl.SPEED_DOWNLOAD) #平均下载速度 c.getinfo(pycurl.SPEED_UPLOAD) #平均上传速度 c.getinfo(pycurl.HEADER_SIZE) #HTTP头部大小

一、获取网络资源

  步骤:1)创建一个pycurl.Curl实例;2)使用setopt设置选项;3)使用perform执行

二、将网页内容存储大文件中

  

 1 def header_function(info):
 2     print (info)
 3 
 4 def get_pycurl(url):
 5     # 创建一个buffer,要使用BytesIO
 6     buffer = io.BytesIO()
 7     # 创建实例
 8     c = pycurl.Curl()
 9     c.setopt(pycurl.URL, url)
10     c.setopt(pycurl.WRITEFUNCTION, buffer.write)
11     c.setopt(pycurl.HEADERFUNCTION,header_function)
12     c.perform()
13     c.close()
14     
15     body = buffer.getvalue().decode('utf-8')
16 #    print (body)
17 
18 def write_file(path, url):
19     with open(path, 'wb') as f:
20         c = pycurl.Curl()
21         c.setopt(pycurl.URL, url)
22         c.setopt(pycurl.WRITEDATA, f)
23         c.perform()
24         c.close()
25     print ('写入成功')
26     
27 def get_content(url):
28     res = urllib.request.urlopen(url)
29     content = res.read().decode('utf-8')
30     print (content)
31     
32     
33 def main():
34 #    root = Tk()
35 #    button_my = my_button(root, 'a', 'b', action)
36 #    root.mainloop()
37 #    c1 = myClass()
38 #    c1.get_name()
39 #    c1.get_file('deng.txt')
40 #    print ()
41 #    get_file('deng.txt')
42 #    get_pycurl('http://www.baidu.com')
43     url = 'http://www.baidu.com'
44     path = 'e:/deng.txt'
45 #    get_content(url)
46 #    get_pycurl(url)
47     write_file(path, url)
48     
49 if __name__ == '__main__':
50     main()

 

 

  

posted @ 2017-09-27 09:49  今夜无风  阅读(645)  评论(0编辑  收藏  举报