|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +from urllib import request, parse |
| 5 | + |
| 6 | +# get: |
| 7 | + |
| 8 | +with request.urlopen('https://api.douban.com/v2/book/2129650') as f: |
| 9 | + data = f.read() |
| 10 | + print('Status:', f.status, f.reason) |
| 11 | + for k, v in f.getheaders(): |
| 12 | + print('%s: %s' % (k, v)) |
| 13 | + print('Data:', data.decode('utf-8')) |
| 14 | + |
| 15 | +# advanced get: |
| 16 | + |
| 17 | +req = request.Request('http://www.douban.com/') |
| 18 | +req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') |
| 19 | +with request.urlopen(req) as f: |
| 20 | + print('Status:', f.status, f.reason) |
| 21 | + for k, v in f.getheaders(): |
| 22 | + print('%s: %s' % (k, v)) |
| 23 | + print('Data:', f.read().decode('utf-8')) |
| 24 | + |
| 25 | +# post: |
| 26 | + |
| 27 | +print('Login to weibo.cn...') |
| 28 | +email = input('Email: ') |
| 29 | +passwd = input('Password: ') |
| 30 | +login_data = parse.urlencode([ |
| 31 | + ('username', email), |
| 32 | + ('password', passwd), |
| 33 | + ('entry', 'mweibo'), |
| 34 | + ('client_id', ''), |
| 35 | + ('savestate', '1'), |
| 36 | + ('ec', ''), |
| 37 | + ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F%3Fjumpfrom%3Dweibocom&jumpfrom=weibocom') |
| 38 | +]) |
| 39 | + |
| 40 | +req = request.Request('https://passport.weibo.cn/sso/login') |
| 41 | +req.add_header('Origin', 'https://passport.weibo.cn') |
| 42 | +req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25') |
| 43 | +req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F%3Fjumpfrom%3Dweibocom') |
| 44 | + |
| 45 | +with request.urlopen(req, data=login_data.encode('utf-8')) as f: |
| 46 | + print('Status:', f.status, f.reason) |
| 47 | + for k, v in f.getheaders(): |
| 48 | + print('%s: %s' % (k, v)) |
| 49 | + print('Data:', f.read().decode('utf-8')) |
| 50 | + |
| 51 | +# with proxy and proxy auth: |
| 52 | + |
| 53 | +proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'}) |
| 54 | +proxy_auth_handler = urllib.request.ProxyBasicAuthHandler() |
| 55 | +proxy_auth_handler.add_password('realm', 'host', 'username', 'password') |
| 56 | +opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) |
| 57 | +with opener.open('http://www.example.com/login.html') as f: |
| 58 | + pass |
0 commit comments