1、模块说明 requests是使用Apache2 licensed 许可证的HTTP库。 用python编写。 比urllib2模块更简洁。 Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和POST数据自动编码。 在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得人性化,使用Requests可以轻而易举的完成浏览器可有的任何操作。 现代,国际化,友好。 requests会自动实现持久连接keep-alive 2、基础入门 1)导入模块 import requests 2)发送请求的简洁 示例代码:获取一个网页(个人github) import requests r = requests.get('https://github.com/Ranxf') # 最基本的不带参数的get请求 r1 = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'}) # 带参数的get请求 我们就可以使用该方式使用以下各种方法 1 requests.get(‘https://github.com/timeline.json’) # GET请求 2 requests.post(“http://httpbin.org/post”) # POST请求 3 requests.put(“http://httpbin.org/put”) # PUT请求 4 requests.delete(“http://httpbin.org/delete”) # DELETE请求 5 requests.head(“http://httpbin.org/get”) # HEAD请求 6 requests.options(“http://httpbin.org/get” ) # OPTIONS请求 3)为url传递参数 >>> url_params = {'key':'value'} # 字典传递参数,如果值为None的键不会被添加到url中 >>> r = requests.get('your url',params = url_params) >>> print(r.url) your url?key=value 4)响应的内容 r.encoding #获取当前的编码 r.encoding = 'utf-8' #设置编码 r.text #以encoding解析返回内容。字符串方式的响应体,会自动根据响应头部的字符编码进行解码。 r.content #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。 r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None r.status_code #响应状态码 r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() r.ok # 查看r.ok的布尔值便可以知道是否登陆成功 #*特殊方法*# r.json() #Requests中内置的JSON解码器,以json形式返回,前提返回的内容确保是json格式的,不然解析出错会抛异常 r.raise_for_status() #失败请求(非200响应)抛出异常 post发送json请求: 1 import requests 2 import json 3 4 r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'})) 5 print(r.json()) 5)定制头和cookie信息 header = {'user-agent': 'my-app/0.0.1''} cookie = {'key':'value'} r = requests.get/post('your url',headers=header,cookies=cookie) data = {'some': 'data'} headers = {'content-type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers) print(r.text) 6)响应状态码 使用requests方法后,会返回一个response对象,其存储了服务器响应的内容,如上实例中已经提到的 r.text、r.status_code……获取文本方式的响应体实例:当你访问 r.text 之时,会使用其响应的文本编码进行解码,并且你可以修改其编码让 r.text 使用自定义的编码进行解码。 1 r = requests.get('http://www.itwhy.org') 2 print(r.text, '\n{}\n'.format('*'*79), r.encoding) 3 r.encoding = 'GBK' 4 print(r.text, '\n{}\n'.format('*'*79), r.encoding) 示例代码: 1 import requests 2 3 r = requests.get('https://github.com/Ranxf') # 最基本的不带参数的get请求 4 print(r.status_code) # 获取返回状态 5 r1 = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'}) # 带参数的get请求 6 print(r1.url) 7 print(r1.text) # 打印解码后的返回数据 运行结果: /usr/bin/python3.5 /home/rxf/python3_1000/1000/python3_server/python3_requests/demo1.py 200 http://dict.baidu.com/s?wd=python ………… Process finished with exit code 0 r.status_code #如果不是200,可以使用 r.raise_for_status() 抛出异常 7)响应 r.headers #返回字典类型,头信息 r.requests.headers #返回发送到服务器的头信息 r.cookies #返回cookie r.history #返回重定向信息,当然可以在请求是加上allow_redirects = false 阻止重定向 8)超时 r = requests.get('url',timeout=1) #设置秒数超时,仅对于连接有效 9)会话对象,能够跨请求保持某些参数 s = requests.Session() s.auth = ('auth','passwd') s.headers = {'key':'value'} r = s.get('url') r1 = s.get('url1') 10)代理 proxies = {'http':'ip1','https':'ip2' } requests.get('url',proxies=proxies) 汇总: # HTTP请求类型 # get类型 r = requests.get('https://github.com/timeline.json') # post类型 r = requests.post("http://m.ctrip.com/post") # put类型 r = requests.put("http://m.ctrip.com/put") # delete类型 r = requests.delete("http://m.ctrip.com/delete") # head类型 r = requests.head("http://m.ctrip.com/head") # options类型 r = requests.options("http://m.ctrip.com/get") # 获取响应内容 print(r.content) #以字节的方式去显示,中文显示为字符 print(r.text) #以文本的方式去显示 #URL传递参数 payload = {'keyword': '香港', 'salecityid': '2'} r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) print(r.url) #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=香港 #获取/修改网页编码 r = requests.get('https://github.com/timeline.json') print (r.encoding) #json处理 r = requests.get('https://github.com/timeline.json') print(r.json()) # 需要先import json # 定制请求头 url = 'http://m.ctrip.com' headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'} r = requests.post(url, headers=headers) print (r.request.headers) #复杂post请求 url = 'http://m.ctrip.com' payload = {'some': 'data'} r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下 # post多部分编码文件 url = 'http://m.ctrip.com' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files) # 响应状态码 r = requests.get('http://m.ctrip.com') print(r.status_code) # 响应头 r = requests.get('http://m.ctrip.com') print (r.headers) print (r.headers['Content-Type']) print (r.headers.get('content-type')) #访问响应头部分内容的两种方式 # Cookies url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) r.cookies['example_cookie_name'] #读取cookies url = 'http://m.ctrip.com/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies) #发送cookies #设置超时时间 r = requests.get('http://m.ctrip.com', timeout=0.001) #设置访问代理 proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.100:4444", } r = requests.get('http://m.ctrip.com', proxies=proxies) #如果代理需要用户名和密码,则需要这样: proxies = { "http": "http://user:pass@10.10.1.10:3128/", } # HTTP请求类型 # get类型 r = requests.get('https://github.com/timeline.json') # post类型 r = requests.post("http://m.ctrip.com/post") # put类型 r = requests.put("http://m.ctrip.com/put") # delete类型 r = requests.delete("http://m.ctrip.com/delete") # head类型 r = requests.head("http://m.ctrip.com/head") # options类型 r = requests.options("http://m.ctrip.com/get") # 获取响应内容 print(r.content) #以字节的方式去显示,中文显示为字符 print(r.text) #以文本的方式去显示 #URL传递参数 payload = {'keyword': '香港', 'salecityid': '2'} r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) print(r.url) #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=香港 #获取/修改网页编码 r = requests.get('https://github.com/timeline.json') print (r.encoding) #json处理 r = requests.get('https://github.com/timeline.json') print(r.json()) # 需要先import json # 定制请求头 url = 'http://m.ctrip.com' headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'} r = requests.post(url, headers=headers) print (r.request.headers) #复杂post请求 url = 'http://m.ctrip.com' payload = {'some': 'data'} r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下 # post多部分编码文件 url = 'http://m.ctrip.com' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files) # 响应状态码 r = requests.get('http://m.ctrip.com') print(r.status_code) # 响应头 r = requests.get('http://m.ctrip.com') print (r.headers) print (r.headers['Content-Type']) print (r.headers.get('content-type')) #访问响应头部分内容的两种方式 # Cookies url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) r.cookies['example_cookie_name'] #读取cookies url = 'http://m.ctrip.com/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies) #发送cookies #设置超时时间 r = requests.get('http://m.ctrip.com', timeout=0.001) #设置访问代理 proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.100:4444", } r = requests.get('http://m.ctrip.com', proxies=proxies) #如果代理需要用户名和密码,则需要这样: proxies = { "http": "http://user:pass@10.10.1.10:3128/", } 3、示例代码 GET请求 1 # 1、无参数实例 2 3 import requests 4 5 ret = requests.get('https://github.com/timeline.json') 6 7 print(ret.url) 8 print(ret.text) 9 10 11 12 # 2、有参数实例 13 14 import requests 15 16 payload = {'key1': 'value1', 'key2': 'value2'} 17 ret = requests.get("http://httpbin.org/get", params=payload) 18 19 print(ret.url) 20 print(ret.text) POST请求 # 1、基本POST实例 import requests payload = {'key1': 'value1', 'key2': 'value2'} ret = requests.post("http://httpbin.org/post", data=payload) print(ret.text) # 2、发送请求头和数据实例 import requests import json url = 'https://api.github.com/some/endpoint' payload = {'some': 'data'} headers = {'content-type': 'application/json'} ret = requests.post(url, data=json.dumps(payload), headers=headers) print(ret.text) print(ret.cookies) 请求参数 def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')`` or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """ 参数列表 请求参数 请求参数 def param_method_url(): # requests.request(method='get', url='http://127.0.0.1:8000/test/') # requests.request(method='post', url='http://127.0.0.1:8000/test/') pass def param_param(): # - 可以是字典 # - 可以是字符串 # - 可以是字节(ascii编码以内) # requests.request(method='get', # url='http://127.0.0.1:8000/test/', # params={'k1': 'v1', 'k2': '水电费'}) # requests.request(method='get', # url='http://127.0.0.1:8000/test/', # params="k1=v1&k2=水电费&k3=v3&k3=vv3") # requests.request(method='get', # url='http://127.0.0.1:8000/test/', # params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding='utf8')) # 错误 # requests.request(method='get', # url='http://127.0.0.1:8000/test/', # params=bytes("k1=v1&k2=水电费&k3=v3&k3=vv3", encoding='utf8')) pass def param_data(): # 可以是字典 # 可以是字符串 # 可以是字节 # 可以是文件对象 # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # data={'k1': 'v1', 'k2': '水电费'}) # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # data="k1=v1; k2=v2; k3=v3; k3=v4" # ) # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # data="k1=v1;k2=v2;k3=v3;k3=v4", # headers={'Content-Type': 'application/x-www-form-urlencoded'} # ) # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # data=open('data_file.py', mode='r', encoding='utf-8'), # 文件内容是:k1=v1;k2=v2;k3=v3;k3=v4 # headers={'Content-Type': 'application/x-www-form-urlencoded'} # ) pass def param_json(): # 将json中对应的数据进行序列化成一个字符串,json.dumps(...) # 然后发送到服务器端的body中,并且Content-Type是 {'Content-Type': 'application/json'} requests.request(method='POST', url='http://127.0.0.1:8000/test/', json={'k1': 'v1', 'k2': '水电费'}) def param_headers(): # 发送请求头到服务器端 requests.request(method='POST', url='http://127.0.0.1:8000/test/', json={'k1': 'v1', 'k2': '水电费'}, headers={'Content-Type': 'application/x-www-form-urlencoded'} ) def param_cookies(): # 发送Cookie到服务器端 requests.request(method='POST', url='http://127.0.0.1:8000/test/', data={'k1': 'v1', 'k2': 'v2'}, cookies={'cook1': 'value1'}, ) # 也可以使用CookieJar(字典形式就是在此基础上封装) from http.cookiejar import CookieJar from http.cookiejar import Cookie obj = CookieJar() obj.set_cookie(Cookie(version=0, name='c1', value='v1', port=None, domain='', path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False, port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False) ) requests.request(method='POST', url='http://127.0.0.1:8000/test/', data={'k1': 'v1', 'k2': 'v2'}, cookies=obj) def param_files(): # 发送文件 # file_dict = { # 'f1': open('readme', 'rb') # } # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # files=file_dict) # 发送文件,定制文件名 # file_dict = { # 'f1': ('test.txt', open('readme', 'rb')) # } # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # files=file_dict) # 发送文件,定制文件名 # file_dict = { # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf") # } # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # files=file_dict) # 发送文件,定制文件名 # file_dict = { # 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf", 'application/text', {'k1': '0'}) # } # requests.request(method='POST', # url='http://127.0.0.1:8000/test/', # files=file_dict) pass def param_auth(): from requests.auth import HTTPBasicAuth, HTTPDigestAuth ret = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('wupeiqi', 'sdfasdfasdf')) print(ret.text) # ret = requests.get('http://192.168.1.1', # auth=HTTPBasicAuth('admin', 'admin')) # ret.encoding = 'gbk' # print(ret.text) # ret = requests.get('http://httpbin.org/digest-auth/auth/user/pass', auth=HTTPDigestAuth('user', 'pass')) # print(ret) # def param_timeout(): # ret = requests.get('http://google.com/', timeout=1) # print(ret) # ret = requests.get('http://google.com/', timeout=(5, 1)) # print(ret) pass def param_allow_redirects(): ret = requests.get('http://127.0.0.1:8000/test/', allow_redirects=False) print(ret.text) def param_proxies(): # proxies = { # "http": "61.172.249.96:80", # "https": "http://61.185.219.126:3128", # } # proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'} # ret = requests.get("http://www.proxy360.cn/Proxy", proxies=proxies) # print(ret.headers) # from requests.auth import HTTPProxyAuth # # proxyDict = { # 'http': '77.75.105.165', # 'https': '77.75.105.165' # } # auth = HTTPProxyAuth('username', 'mypassword') # # r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth) # print(r.text) pass def param_stream(): ret = requests.get('http://127.0.0.1:8000/test/', stream=True) print(ret.content) ret.close() # from contextlib import closing # with closing(requests.get('http://httpbin.org/get', stream=True)) as r: # # 在此处理响应。 # for i in r.iter_content(): # print(i) def requests_session(): import requests session = requests.Session() ### 1、首先登陆任何页面,获取cookie i1 = session.get(url="http://dig.chouti.com/help/service") ### 2、用户登陆,携带上一次的cookie,后台对cookie中的 gpsd 进行授权 i2 = session.post( url="http://dig.chouti.com/login", data={ 'phone': "8615131255089", 'password': "xxxxxx", 'oneMonth': "" } ) i3 = session.post( url="http://dig.chouti.com/link/vote?linksId=8589623", ) print(i3.text) 参数示例代码 json请求: #! /usr/bin/python3 import requests import json class url_request(): def __init__(self): ''' init ''' if __name__ == '__main__': heard = {'Content-Type': 'application/json'} payload = {'CountryName': '中国', 'ProvinceName': '四川省', 'L1CityName': 'chengdu', 'L2CityName': 'yibing', 'TownName': '', 'Longitude': '107.33393', 'Latitude': '33.157131', 'Language': 'CN'} r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity", heards=heard, data=payload) data = r.json() if r.status_code!=200: print('LBSLocateCity API Error' + str(r.status_code)) print(data['CityEntities'][0]['CityID']) # 打印返回json中的某个key的value print(data['ResponseStatus']['Ack']) print(json.dump(data, indent=4, sort_keys=True, ensure_ascii=False)) # 树形打印json,ensure_ascii必须设为False否则中文会显示为unicode Xml请求: #! /usr/bin/python3 import requests class url_request(): def __init__(self): """init""" if __name__ == '__main__': heards = {'Content-type': 'text/xml'} XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>' url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx' r = requests.post(url=url, heards=heards, data=XML) data = r.text print(data) 状态异常处理 import requests URL = 'http://ip.taobao.com/service/getIpInfo.php' # 淘宝IP地址库API try: r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1) r.raise_for_status() # 如果响应状态码不是 200,就主动抛出异常 except requests.RequestException as e: print(e) else: result = r.json() print(type(result), result, sep='\n') 上传文件 使用request模块,也可以上传文件,文件的类型会自动进行处理: import requests url = 'http://127.0.0.1:8080/upload' files = {'file': open('/home/rxf/test.jpg', 'rb')} #files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))} #显式的设置文件名 r = requests.post(url, files=files) print(r.text) request更加方便的是,可以把字符串当作文件进行上传: import requests url = 'http://127.0.0.1:8080/upload' files = {'file': ('test.txt', b'Hello Requests.')} #必需显式的设置文件名 r = requests.post(url, files=files) print(r.text) 6) 身份验证 基本身份认证(HTTP Basic Auth) import requests from requests.auth import HTTPBasicAuth r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd')) # r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd')) # 简写 print(r.json()) 另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的: requests.get(URL, auth=HTTPDigestAuth('user', 'pass') Cookies与会话对象 如果某个响应中包含一些Cookie,你可以快速访问它们: import requests r = requests.get('http://www.google.com.hk/') print(r.cookies['NID']) print(tuple(r.cookies)) 要想发送你的cookies到服务器,可以使用 cookies 参数: import requests url = 'http://httpbin.org/cookies' cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'} # 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。 r = requests.get(url, cookies=cookies) print(r.json()) 会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。下面就来一个真正的实例,如下是快盘签到脚本: import requests headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept-Language': 'en-us;q=0.5,en;q=0.3', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} s = requests.Session() s.headers.update(headers) # s.auth = ('superuser', '123') s.get('https://www.kuaipan.cn/account_login.htm') _URL = 'http://www.kuaipan.cn/index.php' s.post(_URL, params={'ac':'account', 'op':'login'}, data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'}) r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'}) print(r.json()) s.get(_URL, params={'ac':'common', 'op':'usersign'}) requests模块抓取网页源码并保存到文件示例 这是一个基本的文件保存操作,但这里有几个值得注意的问题: 1.安装requests包,命令行输入pip install requests即可自动安装。很多人推荐使用requests,自带的urllib.request也可以抓取网页源码 2.open方法encoding参数设为utf-8,否则保存的文件会出现乱码。 3.如果直接在cmd中输出抓取的内容,会提示各种编码错误,所以保存到文件查看。 4.with open方法是更好的写法,可以自动操作完毕后释放资源 #! /urs/bin/python3 import requests '''requests模块抓取网页源码并保存到文件示例''' html = requests.get("http://www.baidu.com") with open('test.txt', 'w', encoding='utf-8') as f: f.write(html.text) '''读取一个txt文件,每次读取一行,并保存到另一个txt文件中的示例''' ff = open('testt.txt', 'w', encoding='utf-8') with open('test.txt', encoding="utf-8") as f: for line in f: ff.write(line) ff.close() 因为在命令行中打印每次读取一行的数据,中文会出现编码错误,所以每次读取一行并保存到另一个文件,这样来测试读取是否正常。(注意open的时候制定encoding编码方式)
查看详情
python 线程与进程简介 进程与线程的历史 我们都知道计算机是由硬件和软件组成的。硬件中的CPU是计算机的核心,它承担计算机的所有任务。 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源的管理和分配、任务的调度。 程序是运行在系统上的具有某种功能的软件,比如说浏览器,音乐播放器等。 每次执行程序的时候,都会完成一定的功能,比如说浏览器帮我们打开网页,为了保证其独立性,就需要一个专门的管理和控制执行程序的数据结构——进程控制块。 进程就是一个程序在一个数据集上的一次动态执行过程。 进程一般由程序、数据集、进程控制块三部分组成。我们编写的程序用来描述进程要完成哪些功能以及如何完成;数据集则是程序在执行过程中所需要使用的资源;进程控制块用来记录进程的外部特征,描述进程的执行变化过程,系统可以利用它来控制和管理进程,它是系统感知进程存在的唯一标志。 在早期的操作系统里,计算机只有一个核心,进程执行程序的最小单位,任务调度采用时间片轮转的抢占式方式进行进程调度。每个进程都有各自的一块独立的内存,保证进程彼此间的内存地址空间的隔离。 随着计算机技术的发展,进程出现了很多弊端,一是进程的创建、撤销和切换的开销比较大,二是由于对称多处理机(对称多处理机(SymmetricalMulti-Processing)又叫SMP,是指在一个计算机上汇集了一组处理器(多CPU),各CPU之间共享内存子系统以及总线结构)的出现,可以满足多个运行单位,而多进程并行开销过大。 这个时候就引入了线程的概念。 线程也叫轻量级进程,它是一个基本的CPU执行单元,也是程序执行过程中的最小单元,由线程ID、程序计数器、寄存器集合 和堆栈共同组成。线程的引入减小了程序并发执行时的开销,提高了操作系统的并发性能。 线程没有自己的系统资源,只拥有在运行时必不可少的资源。但线程可以与同属与同一进程的其他线程共享进程所拥有的其他资源。 进程与线程之间的关系 线程是属于进程的,线程运行在进程空间内,同一进程所产生的线程共享同一内存空间,当进程退出时该进程所产生的线程都会被强制退出并清除。线程可与属于同一进程的其它线程共享进程所拥有的全部资源,但是其本身基本上不拥有系统资源,只拥有一点在运行中必不可少的信息(如程序计数器、一组寄存器和栈)。 python 线程 Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。 1、threading模块 threading 模块建立在 _thread 模块之上。thread 模块以低级、原始的方式来处理和控制线程,而 threading 模块通过对 thread 进行二次封装,提供了更方便的 api 来处理线程。 import threading import time def worker(num): """ thread worker function :return: """ time.sleep(1) print("The num is %d" % num) return for i in range(20): t = threading.Thread(target=worker,args=(i,),name=“t.%d” % i) t.start() 上述代码创建了20个“前台”线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。 Thread方法说明 t.start() : 激活线程, t.getName() : 获取线程的名称 t.setName() : 设置线程的名称 t.name : 获取或设置线程的名称 t.is_alive() : 判断线程是否为激活状态 t.isAlive() :判断线程是否为激活状态 t.setDaemon() 设置为后台线程或前台线程(默认:False);通过一个布尔值设置线程是否为守护线程,必须在执行start()方法之后才可以使用。如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止;如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止 t.isDaemon() : 判断是否为守护线程 t.ident :获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。 t.join() :逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义 t.run() :线程被cpu调度后自动执行线程对象的run方法 2、线程锁threading.RLock和threading.Lock 由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,CPU接着执行其他线程。为了保证数据的准确性,引入了锁的概念。所以,可能出现如下问题: 例:假设列表A的所有元素就为0,当一个线程从前向后打印列表的所有元素,另外一个线程则从后向前修改列表的元素为1,那么输出的时候,列表的元素就会一部分为0,一部分为1,这就导致了数据的不一致。锁的出现解决了这个问题。 import threading import time globals_num = 0 lock = threading.RLock() def Func(): lock.acquire() # 获得锁 global globals_num globals_num += 1 time.sleep(1) print(globals_num) lock.release() # 释放锁 for i in range(10): t = threading.Thread(target=Func) t.start() 3、threading.RLock和threading.Lock 的区别 RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。 如果使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的琐。 import threading lock = threading.Lock() #Lock对象 lock.acquire() lock.acquire() #产生了死琐。 lock.release() lock.release() import threading rLock = threading.RLock() #RLock对象 rLock.acquire() rLock.acquire() #在同一线程内,程序不会堵塞。 rLock.release() rLock.release() 4、threading.Event python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。 事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。 clear:将“Flag”设置为False set:将“Flag”设置为True Event.isSet() :判断标识位是否为Ture。 import threading def do(event): print('start') event.wait() print('execute') event_obj = threading.Event() for i in range(10): t = threading.Thread(target=do, args=(event_obj,)) t.start() event_obj.clear() inp = input('input:') if inp == 'true': event_obj.set() 当线程执行的时候,如果flag为False,则线程会阻塞,当flag为True的时候,线程不会阻塞。它提供了本地和远程的并发性。 5、threading.Condition 一个condition变量总是与某些类型的锁相联系,这个可以使用默认的情况或创建一个,当几个condition变量必须共享和同一个锁的时候,是很有用的。锁是conditon对象的一部分:没有必要分别跟踪。 condition变量服从上下文管理协议:with语句块封闭之前可以获取与锁的联系。 acquire() 和 release() 会调用与锁相关联的相应的方法。 其他和锁关联的方法必须被调用,wait()方法会释放锁,当另外一个线程使用 notify() or notify_all()唤醒它之前会一直阻塞。一旦被唤醒,wait()会重新获得锁并返回, Condition类实现了一个conditon变量。 这个conditiaon变量允许一个或多个线程等待,直到他们被另一个线程通知。 如果lock参数,被给定一个非空的值,,那么他必须是一个lock或者Rlock对象,它用来做底层锁。否则,会创建一个新的Rlock对象,用来做底层锁。 wait(timeout=None) : 等待通知,或者等到设定的超时时间。当调用这wait()方法时,如果调用它的线程没有得到锁,那么会抛出一个RuntimeError 异常。 wati()释放锁以后,在被调用相同条件的另一个进程用notify() or notify_all() 叫醒之前 会一直阻塞。wait() 还可以指定一个超时时间。 如果有等待的线程,notify()方法会唤醒一个在等待conditon变量的线程。notify_all() 则会唤醒所有在等待conditon变量的线程。 注意: notify()和notify_all()不会释放锁,也就是说,线程被唤醒后不会立刻返回他们的wait() 调用。除非线程调用notify()和notify_all()之后放弃了锁的所有权。 在典型的设计风格里,利用condition变量用锁去通许访问一些共享状态,线程在获取到它想得到的状态前,会反复调用wait()。修改状态的线程在他们状态改变时调用 notify() or notify_all(),用这种方式,线程会尽可能的获取到想要的一个等待者状态。 例子: 生产者-消费者模型, import threading import time def consumer(cond): with cond: print("consumer before wait") cond.wait() print("consumer after wait") def producer(cond): with cond: print("producer before notifyAll") cond.notifyAll() print("producer after notifyAll") condition = threading.Condition() c1 = threading.Thread(name="c1", target=consumer, args=(condition,)) c2 = threading.Thread(name="c2", target=consumer, args=(condition,)) p = threading.Thread(name="p", target=producer, args=(condition,)) c1.start() time.sleep(2) c2.start() time.sleep(2) p.start() 6、queue模块 Queue 就是对队列,它是线程安全的 举例来说,我们去麦当劳吃饭。饭店里面有厨师职位,前台负责把厨房做好的饭卖给顾客,顾客则去前台领取做好的饭。这里的前台就相当于我们的队列。形成管道样,厨师做好饭通过前台传送给顾客,所谓单向队列 这个模型也叫生产者-消费者模型。 import queue q = queue.Queue(maxsize=0) # 构造一个先进显出队列,maxsize指定队列长度,为0 时,表示队列长度无限制。 q.join() # 等到队列为kong的时候,在执行别的操作 q.qsize() # 返回队列的大小 (不可靠) q.empty() # 当队列为空的时候,返回True 否则返回False (不可靠) q.full() # 当队列满的时候,返回True,否则返回False (不可靠) q.put(item, block=True, timeout=None) # 将item放入Queue尾部,item必须存在,可以参数block默认为True,表示当队列满时,会等待队列给出可用位置, 为False时为非阻塞,此时如果队列已满,会引发queue.Full 异常。 可选参数timeout,表示 会阻塞设置的时间,过后, 如果队列无法给出放入item的位置,则引发 queue.Full 异常 q.get(block=True, timeout=None) # 移除并返回队列头部的一个值,可选参数block默认为True,表示获取值的时候,如果队列为空,则阻塞,为False时,不阻塞, 若此时队列为空,则引发 queue.Empty异常。 可选参数timeout,表示会阻塞设置的时候,过后,如果队列为空,则引发Empty异常。 q.put_nowait(item) # 等效于 put(item,block=False) q.get_nowait() # 等效于 get(item,block=False) 代码如下: #!/usr/bin/env python import Queue import threading message = Queue.Queue(10) def producer(i): while True: message.put(i) def consumer(i): while True: msg = message.get() for i in range(12): t = threading.Thread(target=producer, args=(i,)) t.start() for i in range(10): t = threading.Thread(target=consumer, args=(i,)) t.start() 那就自己做个线程池吧: # 简单往队列中传输线程数 import threading import time import queue class Threadingpool(): def __init__(self,max_num = 10): self.queue = queue.Queue(max_num) for i in range(max_num): self.queue.put(threading.Thread) def getthreading(self): return self.queue.get() def addthreading(self): self.queue.put(threading.Thread) def func(p,i): time.sleep(1) print(i) p.addthreading() if __name__ == "__main__": p = Threadingpool() for i in range(20): thread = p.getthreading() t = thread(target = func, args = (p,i)) t.start() 方法一 #往队列中无限添加任务 import queue import threading import contextlib import time StopEvent = object() class ThreadPool(object): def __init__(self, max_num): self.q = queue.Queue() self.max_num = max_num self.terminal = False self.generate_list = [] self.free_list = [] def run(self, func, args, callback=None): """ 线程池执行一个任务 :param func: 任务函数 :param args: 任务函数所需参数 :param callback: 任务执行失败或成功后执行的回调函数,回调函数有两个参数1、任务函数执行状态;2、任务函数返回值(默认为None,即:不执行回调函数) :return: 如果线程池已经终止,则返回True否则None """ if len(self.free_list) == 0 and len(self.generate_list) < self.max_num: self.generate_thread() w = (func, args, callback,) self.q.put(w) def generate_thread(self): """ 创建一个线程 """ t = threading.Thread(target=self.call) t.start() def call(self): """ 循环去获取任务函数并执行任务函数 """ current_thread = threading.currentThread self.generate_list.append(current_thread) event = self.q.get() # 获取线程 while event != StopEvent: # 判断获取的线程数不等于全局变量 func, arguments, callback = event # 拆分元祖,获得执行函数,参数,回调函数 try: result = func(*arguments) # 执行函数 status = True except Exception as e: # 函数执行失败 status = False result = e if callback is not None: try: callback(status, result) except Exception as e: pass # self.free_list.append(current_thread) # event = self.q.get() # self.free_list.remove(current_thread) with self.work_state(): event = self.q.get() else: self.generate_list.remove(current_thread) def close(self): """ 关闭线程,给传输全局非元祖的变量来进行关闭 :return: """ for i in range(len(self.generate_list)): self.q.put(StopEvent) def terminate(self): """ 突然关闭线程 :return: """ self.terminal = True while self.generate_list: self.q.put(StopEvent) self.q.empty() @contextlib.contextmanager def work_state(self): self.free_list.append(threading.currentThread) try: yield finally: self.free_list.remove(threading.currentThread) def work(i): print(i) return i +1 # 返回给回调函数 def callback(ret): print(ret) pool = ThreadPool(10) for item in range(50): pool.run(func=work, args=(item,),callback=callback) pool.terminate() # pool.close() 方法二 python 进程 multiprocessing是python的多进程管理包,和threading.Thread类似。 1、multiprocessing模块 直接从侧面用subprocesses替换线程使用GIL的方式,由于这一点,multiprocessing模块可以让程序员在给定的机器上充分的利用CPU。在multiprocessing中,通过创建Process对象生成进程,然后调用它的start()方法, from multiprocessing import Process def func(name): print('hello', name) if __name__ == "__main__": p = Process(target=func,args=('zhangyanlin',)) p.start() p.join() # 等待进程执行完毕 在使用并发设计的时候最好尽可能的避免共享数据,尤其是在使用多进程的时候。 如果你真有需要 要共享数据, multiprocessing提供了两种方式。 (1)multiprocessing,Array,Value 数据可以用Value或Array存储在一个共享内存地图里,如下: from multiprocessing import Array,Value,Process def func(a,b): a.value = 3.333333333333333 for i in range(len(b)): b[i] = -b[i] if __name__ == "__main__": num = Value('d',0.0) arr = Array('i',range(11)) c = Process(target=func,args=(num,arr)) d= Process(target=func,args=(num,arr)) c.start() d.start() c.join() d.join() print(num.value) for i in arr: print(i) 输出: 3.1415927 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] 创建num和arr时,“d”和“i”参数由Array模块使用的typecodes创建:“d”表示一个双精度的浮点数,“i”表示一个有符号的整数,这些共享对象将被线程安全的处理。 Array(‘i’, range(10))中的‘i’参数: ‘c’: ctypes.c_char ‘u’: ctypes.c_wchar ‘b’: ctypes.c_byte ‘B’: ctypes.c_ubyte ‘h’: ctypes.c_short ‘H’: ctypes.c_ushort ‘i’: ctypes.c_int ‘I’: ctypes.c_uint ‘l’: ctypes.c_long, ‘L’: ctypes.c_ulong ‘f’: ctypes.c_float ‘d’: ctypes.c_double (2)multiprocessing,Manager 由Manager()返回的manager提供list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Barrier, Queue, Value and Array类型的支持。 from multiprocessing import Process,Manager def f(d,l): d["name"] = "zhangyanlin" d["age"] = 18 d["Job"] = "pythoner" l.reverse() if __name__ == "__main__": with Manager() as man: d = man.dict() l = man.list(range(10)) p = Process(target=f,args=(d,l)) p.start() p.join() print(d) print(l) 输出: {0.25: None, 1: '1', '2': 2} [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Server process manager比 shared memory 更灵活,因为它可以支持任意的对象类型。另外,一个单独的manager可以通过进程在网络上不同的计算机之间共享,不过他比shared memory要慢。 2、进程池(Using a pool of workers) Pool类描述了一个工作进程池,他有几种不同的方法让任务卸载工作进程。 进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。 我们可以用Pool类创建一个进程池, 展开提交的任务给进程池。 例: #apply from multiprocessing import Pool import time def f1(i): time.sleep(0.5) print(i) return i + 100 if __name__ == "__main__": pool = Pool(5) for i in range(1,31): pool.apply(func=f1,args=(i,)) #apply_async def f1(i): time.sleep(0.5) print(i) return i + 100 def f2(arg): print(arg) if __name__ == "__main__": pool = Pool(5) for i in range(1,31): pool.apply_async(func=f1,args=(i,),callback=f2) pool.close() pool.join() 一个进程池对象可以控制工作进程池的哪些工作可以被提交,它支持超时和回调的异步结果,有一个类似map的实现。 processes :使用的工作进程的数量,如果processes是None那么使用 os.cpu_count()返回的数量。 initializer: 如果initializer是None,那么每一个工作进程在开始的时候会调用initializer(*initargs)。 maxtasksperchild:工作进程退出之前可以完成的任务数,完成后用一个心的工作进程来替代原进程,来让闲置的资源被释放。maxtasksperchild默认是None,意味着只要Pool存在工作进程就会一直存活。 context: 用在制定工作进程启动时的上下文,一般使用 multiprocessing.Pool() 或者一个context对象的Pool()方法来创建一个池,两种方法都适当的设置了context 注意:Pool对象的方法只可以被创建pool的进程所调用。 New in version 3.2: maxtasksperchild New in version 3.4: context 进程池的方法 apply(func[, args[, kwds]]) :使用arg和kwds参数调用func函数,结果返回前会一直阻塞,由于这个原因,apply_async()更适合并发执行,另外,func函数仅被pool中的一个进程运行。 apply_async(func[, args[, kwds[, callback[, error_callback]]]]) : apply()方法的一个变体,会返回一个结果对象。如果callback被指定,那么callback可以接收一个参数然后被调用,当结果准备好回调时会调用callback,调用失败时,则用error_callback替换callback。 Callbacks应被立即完成,否则处理结果的线程会被阻塞。 close() : 阻止更多的任务提交到pool,待任务完成后,工作进程会退出。 terminate() : 不管任务是否完成,立即停止工作进程。在对pool对象进程垃圾回收的时候,会立即调用terminate()。 join() : wait工作线程的退出,在调用join()前,必须调用close() or terminate()。这样是因为被终止的进程需要被父进程调用wait(join等价与wait),否则进程会成为僵尸进程。 map(func, iterable[, chunksize])¶ map_async(func, iterable[, chunksize[, callback[, error_callback]]])¶ imap(func, iterable[, chunksize])¶ imap_unordered(func, iterable[, chunksize]) starmap(func, iterable[, chunksize])¶ starmap_async(func, iterable[, chunksize[, callback[, error_back]]]) python 协程 线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。 协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时(保存状态,下次继续)。协程,则只使用一个线程,在一个线程中规定某个代码块执行顺序。 协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程; event loop是协程执行的控制点, 如果你希望执行协程, 就需要用到它们。 event loop提供了如下的特性: 注册、执行、取消延时调用(异步函数) 创建用于通信的client和server协议(工具) 创建和别的程序通信的子进程和协议(工具) 把函数调用送入线程池中 协程示例: import asyncio async def cor1(): print("COR1 start") await cor2() print("COR1 end") async def cor2(): print("COR2") loop = asyncio.get_event_loop() loop.run_until_complete(cor1()) loop.close() 最后三行是重点。 asyncio.get_event_loop() : asyncio启动默认的event loop run_until_complete() : 这个函数是阻塞执行的,知道所有的异步函数执行完成, close() : 关闭event loop。 1、greenlet import greenlet def fun1(): print("12") gr2.switch() print("56") gr2.switch() def fun2(): print("34") gr1.switch() print("78") gr1 = greenlet.greenlet(fun1) gr2 = greenlet.greenlet(fun2) gr1.switch() 2、gevent gevent属于第三方模块需要下载安装包 pip3 install --upgrade pip3 pip3 install gevent import gevent def fun1(): print("www.baidu.com") # 第一步 gevent.sleep(0) print("end the baidu.com") # 第三步 def fun2(): print("www.zhihu.com") # 第二步 gevent.sleep(0) print("end th zhihu.com") # 第四步 gevent.joinall([ gevent.spawn(fun1), gevent.spawn(fun2), ]) 遇到IO操作自动切换: import gevent import requests def func(url): print("get: %s"%url) gevent.sleep(0) date =requests.get(url) ret = date.text print(url,len(ret)) gevent.joinall([ gevent.spawn(func, 'https://www.python.org/'), gevent.spawn(func, 'https://www.yahoo.com/'), gevent.spawn(func, 'https://github.com/'), ]) 工作中用到协程的地方
查看详情
1. 线程基础 1.1. 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2. 线程同步(锁) 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样)。但是当线程需要共享数据时,可能存在数据不同步的问题。考虑这样一种情况:一个列表里所有元素都是0,线程"set"从后向前把所有元素改成1,而线程"print"负责从前往后读取列表并打印。那么,可能线程"set"开始改的时候,线程"print"便来打印列表了,输出就成了一半0一半1,这就是数据的不同步。为了避免这种情况,引入了锁的概念。 锁有两种状态——锁定和未锁定。每当一个线程比如"set"要访问共享数据时,必须先获得锁定;如果已经有别的线程比如"print"获得锁定了,那么就让线程"set"暂停,也就是同步阻塞;等到线程"print"访问完毕,释放锁以后,再让线程"set"继续。经过这样的处理,打印列表时要么全部输出0,要么全部输出1,不会再出现一半0一半1的尴尬场面。 线程与锁的交互如下图所示: 1.3. 线程通信(条件变量) 然而还有另外一种尴尬的情况:列表并不是一开始就有的;而是通过线程"create"创建的。如果"set"或者"print" 在"create"还没有运行的时候就访问列表,将会出现一个异常。使用锁可以解决这个问题,但是"set"和"print"将需要一个无限循环——他们不知道"create"什么时候会运行,让"create"在运行后通知"set"和"print"显然是一个更好的解决方案。于是,引入了条件变量。 条件变量允许线程比如"set"和"print"在条件不满足的时候(列表为None时)等待,等到条件满足的时候(列表已经创建)发出一个通知,告诉"set" 和"print"条件已经有了,你们该起床干活了;然后"set"和"print"才继续运行。 线程与条件变量的交互如下图所示: 1.4. 线程运行和阻塞的状态转换 最后看看线程运行和阻塞状态的转换。 阻塞有三种情况: 同步阻塞是指处于竞争锁定的状态,线程请求锁定时将进入这个状态,一旦成功获得锁定又恢复到运行状态; 等待阻塞是指等待其他线程通知的状态,线程获得条件锁定后,调用“等待”将进入这个状态,一旦其他线程发出通知,线程将进入同步阻塞状态,再次竞争条件锁定; 而其他阻塞是指调用time.sleep()、anotherthread.join()或等待IO时的阻塞,这个状态下线程不会释放已获得的锁定。 tips: 如果能理解这些内容,接下来的主题将是非常轻松的;并且,这些内容在大部分流行的编程语言里都是一样的。(意思就是非看懂不可 >_< 嫌作者水平低找别人的教程也要看懂) 2. thread Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。 ?12345678910111213141516171819202122232425262728293031323334353637383940# encoding: UTF-8import threadimport time # 一个用于在线程中执行的函数def func(): for i in range(5): print 'func' time.sleep(1) # 结束当前线程 # 这个方法与thread.exit_thread()等价 thread.exit() # 当func返回时,线程同样会结束 # 启动一个线程,线程立即开始运行# 这个方法与thread.start_new_thread()等价# 第一个参数是方法,第二个参数是方法的参数thread.start_new(func, ()) # 方法没有参数时需要传入空tuple # 创建一个锁(LockType,不能直接实例化)# 这个方法与thread.allocate_lock()等价lock = thread.allocate() # 判断锁是锁定状态还是释放状态print lock.locked() # 锁通常用于控制对共享资源的访问count = 0 # 获得锁,成功获得锁定后返回True# 可选的timeout参数不填时将一直阻塞直到获得锁定# 否则超时后将返回Falseif lock.acquire(): count += 1 # 释放锁 lock.release() # thread模块提供的线程都将在主线程结束后同时结束time.sleep(6) thread 模块提供的其他方法: thread.interrupt_main(): 在其他线程中终止主线程。 thread.get_ident(): 获得一个代表当前线程的魔法数字,常用于从一个字典中获得线程相关的数据。这个数字本身没有任何含义,并且当线程结束后会被新线程复用。 thread还提供了一个ThreadLocal类用于管理线程相关的数据,名为 thread._local,threading中引用了这个类。 由于thread提供的线程功能不多,无法在主线程结束后继续运行,不提供条件变量等等原因,一般不使用thread模块,这里就不多介绍了。 3. threading threading基于Java的线程模型设计。锁(Lock)和条件变量(Condition)在Java中是对象的基本行为(每一个对象都自带了锁和条件变量),而在Python中则是独立的对象。Python Thread提供了Java Thread的行为的子集;没有优先级、线程组,线程也不能被停止、暂停、恢复、中断。Java Thread中的部分被Python实现了的静态方法在threading中以模块方法的形式提供。 threading 模块提供的常用方法: threading.currentThread(): 返回当前的线程变量。 threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。 threading模块提供的类: Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local. 3.1. Thread Thread是线程类,与Java类似,有两种使用方法,直接传入要运行的方法或从Thread继承并覆盖run(): ?1234567891011121314151617# encoding: UTF-8import threading # 方法1:将要执行的方法作为参数传给Thread的构造方法def func(): print 'func() passed to Thread' t = threading.Thread(target=func)t.start() # 方法2:从Thread继承,并重写run()class MyThread(threading.Thread): def run(self): print 'MyThread extended from Thread' t = MyThread()t.start() 构造方法: Thread(group=None, target=None, name=None, args=(), kwargs={}) group: 线程组,目前还没有实现,库引用中提示必须是None; target: 要执行的方法; name: 线程名; args/kwargs: 要传入方法的参数。 实例方法: isAlive(): 返回线程是否在运行。正在运行指启动后、终止前。 get/setName(name): 获取/设置线程名。 is/setDaemon(bool): 获取/设置是否守护线程。初始值从创建该线程的线程继承。当没有非守护线程仍在运行时,程序将终止。 start(): 启动线程。 join([timeout]): 阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。 一个使用join()的例子: ?1234567891011121314151617181920212223# encoding: UTF-8import threadingimport time def context(tJoin): print 'in threadContext.' tJoin.start() # 将阻塞tContext直到threadJoin终止。 tJoin.join() # tJoin终止后继续执行。 print 'out threadContext.' def join(): print 'in threadJoin.' time.sleep(1) print 'out threadJoin.' tJoin = threading.Thread(target=join)tContext = threading.Thread(target=context, args=(tJoin,)) tContext.start() 运行结果: in threadContext. in threadJoin. out threadJoin. out threadContext. 3.2. Lock Lock(指令锁)是可用的最低级的同步指令。Lock处于锁定状态时,不被特定的线程拥有。Lock包含两种状态——锁定和非锁定,以及两个基本的方法。 可以认为Lock有一个锁定池,当线程请求锁定时,将线程至于池中,直到获得锁定后出池。池中的线程处于状态图中的同步阻塞状态。 构造方法: Lock() 实例方法: acquire([timeout]): 使线程进入同步阻塞状态,尝试获得锁定。 release(): 释放锁。使用前线程必须已获得锁定,否则将抛出异常。 ?1234567891011121314151617181920212223242526272829# encoding: UTF-8import threadingimport time data = 0lock = threading.Lock() def func(): global data print '%s acquire lock...' % threading.currentThread().getName() # 调用acquire([timeout])时,线程将一直阻塞, # 直到获得锁定或者直到timeout秒后(timeout参数可选)。 # 返回是否获得锁。 if lock.acquire(): print '%s get the lock.' % threading.currentThread().getName() data += 1 time.sleep(2) print '%s release lock...' % threading.currentThread().getName() # 调用release()将释放锁。 lock.release() t1 = threading.Thread(target=func)t2 = threading.Thread(target=func)t3 = threading.Thread(target=func)t1.start()t2.start()t3.start() 3.3. RLock RLock(可重入锁)是一个可以被同一个线程请求多次的同步指令。RLock使用了“拥有的线程”和“递归等级”的概念,处于锁定状态时,RLock被某个线程拥有。拥有RLock的线程可以再次调用acquire(),释放锁时需要调用release()相同次数。 可以认为RLock包含一个锁定池和一个初始值为0的计数器,每次成功调用 acquire()/release(),计数器将+1/-1,为0时锁处于未锁定状态。 构造方法: RLock() 实例方法: acquire([timeout])/release(): 跟Lock差不多。 ?12345678910111213141516171819202122232425262728293031323334# encoding: UTF-8import threadingimport time rlock = threading.RLock() def func(): # 第一次请求锁定 print '%s acquire lock...' % threading.currentThread().getName() if rlock.acquire(): print '%s get the lock.' % threading.currentThread().getName() time.sleep(2) # 第二次请求锁定 print '%s acquire lock again...' % threading.currentThread().getName() if rlock.acquire(): print '%s get the lock.' % threading.currentThread().getName() time.sleep(2) # 第一次释放锁 print '%s release lock...' % threading.currentThread().getName() rlock.release() time.sleep(2) # 第二次释放锁 print '%s release lock...' % threading.currentThread().getName() rlock.release() t1 = threading.Thread(target=func)t2 = threading.Thread(target=func)t3 = threading.Thread(target=func)t1.start()t2.start()t3.start() 3.4. Condition Condition(条件变量)通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。 可以认为,除了Lock带有的锁定池外,Condition还包含一个等待池,池中的线程处于状态图中的等待阻塞状态,直到另一个线程调用notify()/notifyAll()通知;得到通知后线程进入锁定池等待锁定。 构造方法: Condition([lock/rlock]) 实例方法: acquire([timeout])/release(): 调用关联的锁的相应方法。 wait([timeout]): 调用这个方法将使线程进入Condition的等待池等待通知,并释放锁。使用前线程必须已获得锁定,否则将抛出异常。 notify(): 调用这个方法将从等待池挑选一个线程并通知,收到通知的线程将自动调用acquire()尝试获得锁定(进入锁定池);其他线程仍然在等待池中。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。 notifyAll(): 调用这个方法将通知等待池中所有的线程,这些线程都将进入锁定池尝试获得锁定。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。 例子是很常见的生产者/消费者模式: ?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# encoding: UTF-8import threadingimport time # 商品product = None# 条件变量con = threading.Condition() # 生产者方法def produce(): global product if con.acquire(): while True: if product is None: print 'produce...' product = 'anything' # 通知消费者,商品已经生产 con.notify() # 等待通知 con.wait() time.sleep(2) # 消费者方法def consume(): global product if con.acquire(): while True: if product is not None: print 'consume...' product = None # 通知生产者,商品已经没了 con.notify() # 等待通知 con.wait() time.sleep(2) t1 = threading.Thread(target=produce)t2 = threading.Thread(target=consume)t2.start()t1.start() 3.5. Semaphore/BoundedSemaphore Semaphore(信号量)是计算机科学史上最古老的同步指令之一。Semaphore管理一个内置的计数器,每当调用acquire()时-1,调用release() 时+1。计数器不能小于0;当计数器为0时,acquire()将阻塞线程至同步锁定状态,直到其他线程调用release()。 基于这个特点,Semaphore经常用来同步一些有“访客上限”的对象,比如连接池。 BoundedSemaphore 与Semaphore的唯一区别在于前者将在调用release()时检查计数器的值是否超过了计数器的初始值,如果超过了将抛出一个异常。 构造方法: Semaphore(value=1): value是计数器的初始值。 实例方法: acquire([timeout]): 请求Semaphore。如果计数器为0,将阻塞线程至同步阻塞状态;否则将计数器-1并立即返回。 release(): 释放Semaphore,将计数器+1,如果使用BoundedSemaphore,还将进行释放次数检查。release()方法不检查线程是否已获得 Semaphore。 ?1234567891011121314151617181920212223242526272829303132333435# encoding: UTF-8import threadingimport time # 计数器初值为2semaphore = threading.Semaphore(2) def func(): # 请求Semaphore,成功后计数器-1;计数器为0时阻塞 print '%s acquire semaphore...' % threading.currentThread().getName() if semaphore.acquire(): print '%s get semaphore' % threading.currentThread().getName() time.sleep(4) # 释放Semaphore,计数器+1 print '%s release semaphore' % threading.currentThread().getName() semaphore.release() t1 = threading.Thread(target=func)t2 = threading.Thread(target=func)t3 = threading.Thread(target=func)t4 = threading.Thread(target=func)t1.start()t2.start()t3.start()t4.start() time.sleep(2) # 没有获得semaphore的主线程也可以调用release# 若使用BoundedSemaphore,t4释放semaphore时将抛出异常print 'MainThread release semaphore without acquire'semaphore.release() 3.6. Event Event(事件)是最简单的线程通信机制之一:一个线程通知事件,其他线程等待事件。Event内置了一个初始为False的标志,当调用set()时设为True,调用clear()时重置为 False。wait()将阻塞线程至等待阻塞状态。 Event其实就是一个简化版的 Condition。Event没有锁,无法使线程进入同步阻塞状态。 构造方法: Event() 实例方法: isSet(): 当内置标志为True时返回True。 set(): 将标志设为True,并通知所有处于等待阻塞状态的线程恢复运行状态。 clear(): 将标志设为False。 wait([timeout]): 如果标志为True将立即返回,否则阻塞线程至等待阻塞状态,等待其他线程调用set()。 ?123456789101112131415161718192021222324# encoding: UTF-8import threadingimport time event = threading.Event() def func(): # 等待事件,进入等待阻塞状态 print '%s wait for event...' % threading.currentThread().getName() event.wait() # 收到事件后进入运行状态 print '%s recv event.' % threading.currentThread().getName() t1 = threading.Thread(target=func)t2 = threading.Thread(target=func)t1.start()t2.start() time.sleep(2) # 发送事件通知print 'MainThread set event.'event.set() 3.7. Timer Timer(定时器)是Thread的派生类,用于在指定时间后调用一个方法。 构造方法: Timer(interval, function, args=[], kwargs={}) interval: 指定的时间 function: 要执行的方法 args/kwargs: 方法的参数 实例方法: Timer从Thread派生,没有增加实例方法。 ?12345678# encoding: UTF-8import threading def func(): print 'hello timer!' timer = threading.Timer(5, func)timer.start() 3.8. local local是一个小写字母开头的类,用于管理 thread-local(线程局部的)数据。对于同一个local,线程无法访问其他线程设置的属性;线程设置的属性不会被其他线程设置的同名属性替换。 可以把local看成是一个“线程-属性字典”的字典,local封装了从自身使用线程作为 key检索对应的属性字典、再使用属性名作为key检索属性值的细节。 ?123456789101112131415# encoding: UTF-8import threading local = threading.local()local.tname = 'main' def func(): local.tname = 'notmain' print local.tname t1 = threading.Thread(target=func)t1.start()t1.join() print local.tname 熟练掌握Thread、Lock、Condition就可以应对绝大多数需要使用线程的场合,某些情况下local也是非常有用的东西。本文的最后使用这几个类展示线程基础中提到的场景: ?12345678910111213141516171819202122232425262728293031323334353637# encoding: UTF-8import threading alist = Nonecondition = threading.Condition() def doSet(): if condition.acquire(): while alist is None: condition.wait() for i in range(len(alist))[::-1]: alist[i] = 1 condition.release() def doPrint(): if condition.acquire(): while alist is None: condition.wait() for i in alist: print i, print condition.release() def doCreate(): global alist if condition.acquire(): if alist is None: alist = [0 for i in range(10)] condition.notifyAll() condition.release() tset = threading.Thread(target=doSet,name='tset')tprint = threading.Thread(target=doPrint,name='tprint')tcreate = threading.Thread(target=doCreate,name='tcreate')tset.start()tprint.start()tcreate.start()
查看详情
一、问题的发现与提出 在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的写法如代码段1: 代码段1: class A: def __init__(self): print "enter A" print "leave A" class B(A): def __init__(self): print "enter B" A.__init__(self) print "leave B" >>> b = B() enter B enter A leave A leave B View Code 即,使用非绑定的类方法(用类名来引用的方法),并在参数列表中,引入待绑定的对象(self),从而达到调用父类的目的。 这样做的缺点是,当一个子类的父类发生变化时(如类B的父类由A变为C时),必须遍历整个类定义,把所有的通过非绑定的方法的类名全部替换过来,例如代码段2, 代码段2: class B(C): # A --> C def __init__(self): print "enter B" C.__init__(self) # A --> C print "leave B" 如果代码简单,这样的改动或许还可以接受。但如果代码量庞大,这样的修改可能是灾难性的。 因此,自Python 2.2开始,Python添加了一个关键字super,来解决这个问题。下面是Python 2.3的官方文档说明: super(type[, object-or-type]) Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes. A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg) New in version 2.2. 从说明来看,可以把类B改写如代码段3: 代码段3: class A(object): # A must be new-style class def __init__(self): print "enter A" print "leave A" class B(C): # A --> C def __init__(self): print "enter B" super(B, self).__init__() print "leave B" 尝试执行上面同样的代码,结果一致,但修改的代码只有一处,把代码的维护量降到最低,是一个不错的用法。因此在我们的开发过程中,super关键字被大量使用,而且一直表现良好。 在我们的印象中,对于super(B, self).__init__()是这样理解的:super(B, self)首先找到B的父类(就是类A),然后把类B的对象self转换为类A的对象(通过某种方式,一直没有考究是什么方式,惭愧),然后“被转换”的类A对象调用自己的__init__函数。考虑到super中只有指明子类的机制,因此,在多继承的类定义中,通常我们保留使用类似代码段1的方法。 有一天某同事设计了一个相对复杂的类体系结构(我们先不要管这个类体系设计得是否合理,仅把这个例子作为一个题目来研究就好),代码如代码段4: 代码段4: class A(object): def __init__(self): print "enter A" print "leave A" class B(object): def __init__(self): print "enter B" print "leave B" class C(A): def __init__(self): print "enter C" super(C, self).__init__() print "leave C" class D(A): def __init__(self): print "enter D" super(D, self).__init__() print "leave D" class E(B, C): def __init__(self): print "enter E" B.__init__(self) C.__init__(self) print "leave E" class F(E, D): def __init__(self): print "enter F" E.__init__(self) D.__init__(self) print "leave F" View Code f = F() result: enter F enter E enter B leave B enter C enter D enter A leave A leave D leave C leave E enter D enter A leave A leave D leave F View Code 明显地,类A和类D的初始化函数被重复调用了2次,这并不是我们所期望的结果!我们所期望的结果是最多只有类A的初始化函数被调用2次——其实这是多继承的类体系必须面对的问题。我们把代码段4的类体系画出来,如下图: object | \ | A | / | B C D \ / | E | \ | F 按我们对super的理解,从图中可以看出,在调用类C的初始化函数时,应该是调用类A的初始化函数,但事实上却调用了类D的初始化函数。好一个诡异的问题! 也就是说,mro中记录了一个类的所有基类的类类型序列。查看mro的记录,发觉包含7个元素,7个类名分别为: F E B C D A object 从而说明了为什么在C.__init__中使用super(C, self).__init__()会调用类D的初始化函数了。 ??? 我们把代码段4改写为: 代码段9: class A(object): def __init__(self): print "enter A" super(A, self).__init__() # new print "leave A" class B(object): def __init__(self): print "enter B" super(B, self).__init__() # new print "leave B" class C(A): def __init__(self): print "enter C" super(C, self).__init__() print "leave C" class D(A): def __init__(self): print "enter D" super(D, self).__init__() print "leave D" class E(B, C): def __init__(self): print "enter E" super(E, self).__init__() # change print "leave E" class F(E, D): def __init__(self): print "enter F" super(F, self).__init__() # change print "leave F" View Code f = F() result: enter F enter E enter B enter C enter D enter A leave A leave D leave C leave B leave E leave F 明显地,F的初始化不仅完成了所有的父类的调用,而且保证了每一个父类的初始化函数只调用一次。 再看类结构: object / \ / A | / \ B-1 C-2 D-2 \ / / E-1 / \ / F E-1,D-2是F的父类,其中表示E类在前,即F(E,D)。 所以初始化顺序可以从类结构图来看出 : F->E->B -->C --> D --> A 由于C,D有同一个父类,因此会先初始化D再是A。 三、延续的讨论 我们再重新看上面的类体系图,如果把每一个类看作图的一个节点,每一个从子类到父类的直接继承关系看作一条有向边,那么该体系图将变为一个有向图。不能发现mro的顺序正好是该有向图的一个拓扑排序序列。 从而,我们得到了另一个结果——Python是如何去处理多继承。支持多继承的传统的面向对象程序语言(如C++)是通过虚拟继承的方式去实现多继承中父类的构造函数被多次调用的问题,而Python则通过mro的方式去处理。 但这给我们一个难题:对于提供类体系的编写者来说,他不知道使用者会怎么使用他的类体系,也就是说,不正确的后续类,可能会导致原有类体系的错误,而且这样的错误非常隐蔽的,也难于发现。 四、小结 1. super并不是一个函数,是一个类名,形如super(B, self)事实上调用了super类的初始化函数, 产生了一个super对象; 2. super类的初始化函数并没有做什么特殊的操作,只是简单记录了类类型和具体实例; 3. super(B, self).func的调用并不是用于调用当前类的父类的func函数; 4. Python的多继承类是通过mro的方式来保证各个父类的函数被逐一调用,而且保证每个父类函数 只调用一次(如果每个类都使用super); 5. 混用super类和非绑定的函数是一个危险行为,这可能导致应该调用的父类函数没有调用或者一 个父类函数被调用多次。
查看详情
一、网络爬虫 网络爬虫又被称为网络蜘蛛,我们可以把互联网想象成一个蜘蛛网,每一个网站都是一个节点,我们可以使用一只蜘蛛去各个网页抓取我们想要的资源。举一个最简单的例子,你在百度和谷歌中输入‘Python',会有大量和Python相关的网页被检索出来,百度和谷歌是如何从海量的网页中检索出你想要的资源,他们靠的就是派出大量蜘蛛去网页上爬取,检索关键字,建立索引数据库,经过复杂的排序算法,结果按照搜索关键字相关度的高低展现给你。 千里之行,始于足下,我们从最基础的开始学习如何写一个网络爬虫,实现语言使用Python。 二、Python如何访问互联网 想要写网络爬虫,第一步是访问互联网,Python如何访问互联网呢? 在Python中,我们使用urllib包访问互联网。(在Python3中,对这个模块做了比较大的调整,以前有urllib和urllib2,在3中对这两个模块做了统一合并,称为urllib包。包下面包含了四个模块,urllib.request,urllib.error,urllib.parse,urllib.robotparser),目前主要使用的是urllib.request。 我们首先举一个最简单的例子,如何获取获取网页的源码: import urllib.request response = urllib.request.urlopen('https://docs.python.org/3/') html = response.read() print(html.decode('utf-8')) 三、Python网络简单使用 首先我们用两个小demo练一下手,一个是使用python代码下载一张图片到本地,另一个是调用有道翻译写一个翻译小软件。 3.1根据图片链接下载图片,代码如下: import urllib.request response = urllib.request.urlopen('http://www.3lian.com/e/ViewImg/index.html?url=http://img16.3lian.com/gif2016/w1/3/d/61.jpg') image = response.read() with open('123.jpg','wb') as f: f.write(image) 其中response是一个对象 输入:response.geturl() ->'http://www.3lian.com/e/ViewImg/index.html?url=http://img16.3lian.com/gif2016/w1/3/d/61.jpg' 输入:response.info() -><http.client.HTTPMessage object at 0x10591c0b8> 输入:print(response.info()) ->Content-Type: text/html Last-Modified: Mon, 27 Sep 2004 01:23:20 GMT Accept-Ranges: bytes ETag: "0f4b59230a4c41:0" Server: Microsoft-IIS/8.0 Date: Sun, 14 Aug 2016 07:16:01 GMT Connection: close Content-Length: 2827 输入:response.getcode() ->200 3.1使用有道词典实现翻译功能 我们想实现翻译功能,我们需要拿到请求链接。首先我们需要进入有道首页,点击翻译,在翻译界面输入要翻译的内容,点击翻译按钮,就会向服务器发起一个请求,我们需要做的就是拿到请求地址和请求参数。 我在此使用谷歌浏览器实现拿到请求地址和请求参数。首先点击右键,点击检查(不同浏览器点击的选项可能不同,同一浏览器的不同版本也可能不同),进入图一所示,从中我们可以拿到请求请求地址和请求参数,在Header中的Form Data中我们可以拿到请求参数。 (图一) 代码段如下: import urllib.request import urllib.parse url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index' data = {} data['type'] = 'AUTO' data['i'] = 'i love you' data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['action'] = 'FY_BY_CLICKBUTTON' data['typoResult'] = 'true' data = urllib.parse.urlencode(data).encode('utf-8') response = urllib.request.urlopen(url,data) html = response.read().decode('utf-8') print(html) 上述代码执行如下: {"type":"EN2ZH_CN","errorCode":0,"elapsedTime":0,"translateResult":[[{"src":"i love you","tgt":"我爱你"}]],"smartResult":{"type":1,"entries":["","我爱你。"]}} 对于上述结果,我们可以看到是一个json串,我们可以对此解析一下,并且对代码进行完善一下: import urllib.request import urllib.parse import json url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index' data = {} data['type'] = 'AUTO' data['i'] = 'i love you' data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['action'] = 'FY_BY_CLICKBUTTON' data['typoResult'] = 'true' data = urllib.parse.urlencode(data).encode('utf-8') response = urllib.request.urlopen(url,data) html = response.read().decode('utf-8') target = json.loads(html) print(target['translateResult'][0][0]['tgt']) 四、规避风险 服务器检测出请求不是来自浏览器,可能会屏蔽掉请求,服务器判断的依据是使用‘User-Agent',我们可以修改改字段的值,来隐藏自己。代码如下: import urllib.request import urllib.parse import json url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index' data = {} data['type'] = 'AUTO' data['i'] = 'i love you' data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['action'] = 'FY_BY_CLICKBUTTON' data['typoResult'] = 'true' data = urllib.parse.urlencode(data).encode('utf-8') req = urllib.request.Request(url, data) req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36') response = urllib.request.urlopen(url, data) html = response.read().decode('utf-8') target = json.loads(html) print(target['translateResult'][0][0]['tgt']) View Code 上述做法虽然可以隐藏自己,但是还有很大问题,例如一个网络爬虫下载图片软件,在短时间内大量下载图片,服务器可以可以根据IP访问次数判断是否是正常访问。所有上述做法还有很大的问题。我们可以通过两种做法解决办法,一是使用延迟,例如5秒内访问一次。另一种办法是使用代理。 延迟访问(休眠5秒,缺点是访问效率低下): import urllib.request import urllib.parse import json import time while True: content = input('please input content(input q exit program):') if content == 'q': break; url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index' data = {} data['type'] = 'AUTO' data['i'] = content data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['action'] = 'FY_BY_CLICKBUTTON' data['typoResult'] = 'true' data = urllib.parse.urlencode(data).encode('utf-8') req = urllib.request.Request(url, data) req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36') response = urllib.request.urlopen(url, data) html = response.read().decode('utf-8') target = json.loads(html) print(target['translateResult'][0][0]['tgt']) time.sleep(5) View Code 代理访问:让代理访问资源,然后讲访问到的资源返回。服务器看到的是代理的IP地址,不是自己地址,服务器就没有办法对你做限制。 步骤: 1,参数是一个字典{'类型' : '代理IP:端口号' } //类型是http,https等 proxy_support = urllib.request.ProxyHandler({}) 2,定制、创建一个opener opener = urllib.request.build_opener(proxy_support) 3,安装opener(永久安装,一劳永逸) urllib.request.install_opener(opener) 3,调用opener(调用的时候使用) opener.open(url) 五、批量下载网络图片 图片下载来源为煎蛋网(http://jandan.net) 图片下载的关键是找到图片的规律,如找到当前页,每一页的图片链接,然后使用循环下载图片。下面是程序代码(待优化,正则表达式匹配,IP代理): import urllib.request import os def url_open(url): req = urllib.request.Request(url) req.add_header('User-Agent','Mozilla/5.0') response = urllib.request.urlopen(req) html = response.read() return html def get_page(url): html = url_open(url).decode('utf-8') a = html.find('current-comment-page') + 23 b = html.find(']',a) return html[a:b] def find_image(url): html = url_open(url).decode('utf-8') image_addrs = [] a = html.find('img src=') while a != -1: b = html.find('.jpg',a,a + 150) if b != -1: image_addrs.append(html[a+9:b+4]) else: b = a + 9 a = html.find('img src=',b) for each in image_addrs: print(each) return image_addrs def save_image(folder,image_addrs): for each in image_addrs: filename = each.split('/')[-1] with open(filename,'wb') as f: img = url_open(each) f.write(img) def download_girls(folder = 'girlimage',pages = 20): os.mkdir(folder) os.chdir(folder) url = 'http://jandan.net/ooxx/' page_num = int(get_page(url)) for i in range(pages): page_num -= i page_url = url + 'page-' + str(page_num) + '#comments' image_addrs = find_image(page_url) save_image(folder,image_addrs) if __name__ == '__main__': download_girls() 代码运行效果如下:
查看详情
1.二维绘图 a. 一维数据集 用 Numpy ndarray 作为数据传入 ply 1. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(1000) y = np.random.standard_normal(10) print "y = %s"% y x = range(len(y)) print "x=%s"% x plt.plot(y) plt.show() 2.操纵坐标轴和增加网格及标签的函数 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(1000) y = np.random.standard_normal(10) plt.plot(y.cumsum()) plt.grid(True) ##增加格点 plt.axis('tight') # 坐标轴适应数据量 axis 设置坐标轴 plt.show() 3.plt.xlim 和 plt.ylim 设置每个坐标轴的最小值和最大值 #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(1000) y = np.random.standard_normal(20) plt.plot(y.cumsum()) plt.grid(True) ##增加格点 plt.xlim(-1,20) plt.ylim(np.min(y.cumsum())- 1, np.max(y.cumsum()) + 1) plt.show() 4. 添加标题和标签 plt.title, plt.xlabe, plt.ylabel 离散点, 线 #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(1000) y = np.random.standard_normal(20) plt.figure(figsize=(7,4)) #画布大小 plt.plot(y.cumsum(),'b',lw = 1.5) # 蓝色的线 plt.plot(y.cumsum(),'ro') #离散的点 plt.grid(True) plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('A simple Plot') plt.show() b. 二维数据集 np.random.seed(2000) y = np.random.standard_normal((10, 2)).cumsum(axis=0) #10行2列 在这个数组上调用cumsum 计算赝本数据在0轴(即第一维)上的总和 print y 1.两个数据集绘图 #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((10, 2)) plt.figure(figsize=(7,5)) plt.plot(y, lw = 1.5) plt.plot(y, 'ro') plt.grid(True) plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('A simple plot') plt.show() 2.添加图例 plt.legend(loc = 0) #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((10, 2)) plt.figure(figsize=(7,5)) plt.plot(y[:,0], lw = 1.5,label = '1st') plt.plot(y[:,1], lw = 1.5, label = '2st') plt.plot(y, 'ro') plt.grid(True) plt.legend(loc = 0) #图例位置自动 plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('A simple plot') plt.show() 3.使用2个 Y轴(左右)fig, ax1 = plt.subplots() ax2 = ax1.twinx() #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((10, 2)) fig, ax1 = plt.subplots() # 关键代码1 plt first data set using first (left) axis plt.plot(y[:,0], lw = 1.5,label = '1st') plt.plot(y[:,0], 'ro') plt.grid(True) plt.legend(loc = 0) #图例位置自动 plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('A simple plot') ax2 = ax1.twinx() #关键代码2 plt second data set using second(right) axis plt.plot(y[:,1],'g', lw = 1.5, label = '2nd') plt.plot(y[:,1], 'ro') plt.legend(loc = 0) plt.ylabel('value 2nd') plt.show() 4.使用两个子图(上下,左右)plt.subplot(211) 通过使用 plt.subplots 函数,可以直接访问底层绘图对象,例如可以用它生成和第一个子图共享 x 轴的第二个子图. #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((10, 2)) plt.figure(figsize=(7,5)) plt.subplot(211) #两行一列,第一个图 plt.plot(y[:,0], lw = 1.5,label = '1st') plt.plot(y[:,0], 'ro') plt.grid(True) plt.legend(loc = 0) #图例位置自动 plt.axis('tight') plt.ylabel('value') plt.title('A simple plot') plt.subplot(212) #两行一列.第二个图 plt.plot(y[:,1],'g', lw = 1.5, label = '2nd') plt.plot(y[:,1], 'ro') plt.grid(True) plt.legend(loc = 0) plt.xlabel('index') plt.ylabel('value 2nd') plt.axis('tight') plt.show() 5.左右子图 有时候,选择两个不同的图标类型来可视化数据可能是必要的或者是理想的.利用子图方法: #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((10, 2)) plt.figure(figsize=(10,5)) plt.subplot(121) #两行一列,第一个图 plt.plot(y[:,0], lw = 1.5,label = '1st') plt.plot(y[:,0], 'ro') plt.grid(True) plt.legend(loc = 0) #图例位置自动 plt.axis('tight') plt.xlabel('index') plt.ylabel('value') plt.title('1st Data Set') plt.subplot(122) plt.bar(np.arange(len(y)), y[:,1],width=0.5, color='g',label = '2nc') plt.grid(True) plt.legend(loc=0) plt.axis('tight') plt.xlabel('index') plt.title('2nd Data Set') plt.show() c.其他绘图样式,散点图,直方图等 1.散点图 scatter #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((1000, 2)) plt.figure(figsize=(7,5)) plt.scatter(y[:,0],y[:,1],marker='o') plt.grid(True) plt.xlabel('1st') plt.ylabel('2nd') plt.title('Scatter Plot') plt.show() 2.直方图 plt.hist #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((1000, 2)) plt.figure(figsize=(7,5)) plt.hist(y,label=['1st','2nd'],bins=25) plt.grid(True) plt.xlabel('value') plt.ylabel('frequency') plt.title('Histogram') plt.show() 3.直方图 同一个图中堆叠 #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((1000, 2)) plt.figure(figsize=(7,5)) plt.hist(y,label=['1st','2nd'],color=['b','g'],stacked=True,bins=20) plt.grid(True) plt.xlabel('value') plt.ylabel('frequency') plt.title('Histogram') plt.show() 4.箱型图 boxplot #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt np.random.seed(2000) y = np.random.standard_normal((1000, 2)) fig, ax = plt.subplots(figsize=(7,4)) plt.boxplot(y) plt.grid(True) plt.setp(ax,xticklabels=['1st' , '2nd']) plt.xlabel('value') plt.ylabel('frequency') plt.title('Histogram') plt.show() 5.绘制函数 from matplotlib.patches import Polygon import numpy as np import matplotlib.pyplot as plt #1. 定义积分函数 def func(x): return 0.5 * np.exp(x)+1 #2.定义积分区间 a,b = 0.5, 1.5 x = np.linspace(0, 2 ) y = func(x) #3.绘制函数图形 fig, ax = plt.subplots(figsize=(7,5)) plt.plot(x,y, 'b',linewidth=2) plt.ylim(ymin=0) #4.核心, 我们使用Polygon函数生成阴影部分,表示积分面积: Ix = np.linspace(a,b) Iy = func(Ix) verts = [(a,0)] + list(zip(Ix, Iy))+[(b,0)] poly = Polygon(verts,facecolor='0.7',edgecolor = '0.5') ax.add_patch(poly) #5.用plt.text和plt.figtext在图表上添加数学公式和一些坐标轴标签。 plt.text(0.5 *(a+b),1,r"$\int_a^b f(x)\mathrm{d}x$", horizontalalignment ='center',fontsize=20) plt.figtext(0.9, 0.075,'$x$') plt.figtext(0.075, 0.9, '$f(x)$') #6. 分别设置x,y刻度标签的位置。 ax.set_xticks((a,b)) ax.set_xticklabels(('$a$','$b$')) ax.set_yticks([func(a),func(b)]) ax.set_yticklabels(('$f(a)$','$f(b)$')) plt.grid(True) 2.金融学图表 matplotlib.finance 1.烛柱图 candlestick #!/etc/bin/python #coding=utf-8 import matplotlib.pyplot as plt import matplotlib.finance as mpf start = (2014, 5,1) end = (2014, 7,1) quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end) # print quotes[:2] fig, ax = plt.subplots(figsize=(8,5)) fig.subplots_adjust(bottom = 0.2) mpf.candlestick(ax, quotes, width=0.6, colorup='b',colordown='r') plt.grid(True) ax.xaxis_date() #x轴上的日期 ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(),rotation=30) #日期倾斜 plt.show() 2. plot_day_summary 该函数提供了一个相当类似的图标类型,使用方法和 candlestick 函数相同,使用类似的参数. 这里开盘价和收盘价不是由彩色矩形表示,而是由两条短水平线表示. #!/etc/bin/python #coding=utf-8 import matplotlib.pyplot as plt import matplotlib.finance as mpf start = (2014, 5,1) end = (2014, 7,1) quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end) # print quotes[:2] fig, ax = plt.subplots(figsize=(8,5)) fig.subplots_adjust(bottom = 0.2) mpf.plot_day_summary(ax, quotes, colorup='b',colordown='r') plt.grid(True) ax.xaxis_date() #x轴上的日期 ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(),rotation=30) #日期倾斜 plt.show() 3.股价数据和成交量 #!/etc/bin/python #coding=utf-8 import matplotlib.pyplot as plt import numpy as np import matplotlib.finance as mpf start = (2014, 5,1) end = (2014, 7,1) quotes = mpf.quotes_historical_yahoo('^GDAXI',start,end) # print quotes[:2] quotes = np.array(quotes) fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8,6)) mpf.candlestick(ax1, quotes, width=0.6,colorup='b',colordown='r') ax1.set_title('Yahoo Inc.') ax1.set_ylabel('index level') ax1.grid(True) ax1.xaxis_date() plt.bar(quotes[:,0] - 0.25, quotes[:, 5], width=0.5) ax2.set_ylabel('volume') ax2.grid(True) ax2.autoscale_view() plt.setp(plt.gca().get_xticklabels(),rotation=30) plt.show() 3.3D 绘图 #!/etc/bin/python #coding=utf-8 import numpy as np import matplotlib.pyplot as plt stike = np.linspace(50, 150, 24) ttm = np.linspace(0.5, 2.5, 24) stike, ttm = np.meshgrid(stike, ttm) print stike[:2] iv = (stike - 100) ** 2 / (100 * stike) /ttm from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(9,6)) ax = fig.gca(projection='3d') surf = ax.plot_surface(stike, ttm, iv, rstride=2, cstride=2, cmap=plt.cm.coolwarm, linewidth=0.5, antialiased=True) ax.set_xlabel('strike') ax.set_ylabel('time-to-maturity') ax.set_zlabel('implied volatility') plt.show()
查看详情