urllib

Python 标准库 urllib2 的使用细节

python 2.x

3.x

from urllib import request

with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
data = f.read()
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', data.decode('utf-8'))

模拟浏览器

from urllib import request

req = request.Request('http://www.douban.com/')
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')
with request.urlopen(req) as f:
print('Status:', f.status, f.reason)
for k, v in f.getheaders():
print('%s: %s' % (k, v))
print('Data:', f.read().decode('utf-8'))

兼容Python2.x 3.x

#!/usr/bin/python
#-*-coding:utf-8-*- import json
import os
import re try:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
except:
from urllib import urlencode
from urllib2 import Request, urlopen def get_token():
req = Request("%s/authorizations/user_token/%s" % (os.environ.get('JPY_HUB_API_URL'), os.environ.get('JPY_USER')))
req.add_header('Authorization', "token %s" % os.environ.get('JPY_HUB_API_TOKEN'))
req.add_header("Host", "192.168.176.100")
req.add_header("Referer", "%s/authorizations/user_token" % os.environ.get('JPY_HUB_API_URL')) data_success = None
data_error = None try:
f = urlopen(req)
except:
print('fail to open')
exit(-1) try:
data_success = f.read()
except:
data_error = {"user_token": ""}
finally:
f.close() if not data_error is None:
data = data_error
else:
data = json.loads(data_success.decode('utf-8')) return data["user_token"] def validate_year(v):
pattern = re.compile(r'^\d{4}$') match = pattern.match(str(v)) if match:
return True
else:
return False def get_data(url):
req = Request(url)
req.add_header('Authorization', "Bearer %s" % get_token())
data_success = None
data_error = None try:
f = urlopen(req)
except:
print('fail to open')
exit(-1) try:
data_success = f.read()
except:
data_error = {"errmsg": "请求发生错误"}
finally:
f.close() if not data_error is None:
data = data_error
else:
data = json.loads(data_success.decode('utf-8')) return data def get_market_list():
url = 'https://xxx.xx.xxx/quote/v1/market/list'
#url = 'http://127.0.0.1:8000/json/market_list.json' return get_data(url) def get_market_holiday(finance_mic, date=None):
mic = ('O', 'N', 'A', 'HK', 'DCE', 'SHFE', 'SZ', 'SS', 'CZCE')
if not finance_mic in mic:
return {"errmsg": "参数错误"} if not date is None and \
not validate_year(date):
return {"errmsg": "参数错误"} search = urlencode([
('finance_mic', finance_mic),
('date', date)
]) url = 'https://xxxx.xx.xxx/quote/v1/market/holiday?%s' % search return get_data(url)

urllib的更多相关文章

  1. python urllib

    在伴随学习爬虫的过程中学习了解的一些基础库和方法总结扩展 1. urllib 在urllib.request module中定义下面的一些方法 urllib.request.urlopen(url,d ...

  2. Python3使用urllib访问网页

    介绍 改教程翻译自python官网的一篇文档. urllib.request是一个用于访问URL(统一资源定位符)的Python模块.它以urlopen函数的形式提供了一个非常简单的接口,可以访问使用 ...

  3. 爬虫初探(1)之urllib.request

    -----------我是小白------------ urllib.request是python3自带的库(python3.x版本特有),我们用它来请求网页,并获取网页源码. # 导入使用库 imp ...

  4. python 3.x urllib学习

    urllib.request import urllib.request as ur url='http://ie.icoa.cn' user_agent = 'Mozilla/4.0 (compat ...

  5. Python爬虫学习(1): urllib的使用

    1.urllib.urlopen 打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作 In [1]: import urllibIn [2]: file = urllib.urlo ...

  6. python2 与 python3 urllib的互相对应关系

    urllib Python2 name Python3 nameurllib.urlopen() Deprecated. See urllib.request.urlopen() which mirr ...

  7. urllib+BeautifulSoup无登录模式爬取豆瓣电影Top250

    对于简单的爬虫任务,尤其对于初学者,urllib+BeautifulSoup足以满足大部分的任务. 1.urllib是Python3自带的库,不需要安装,但是BeautifulSoup却是需要安装的. ...

  8. 初学python之urllib

    urllib.request urlopen()urllib.urlopen(url, data, proxies) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远 ...

  9. urllib.urlretrieve的用法

    urllib.urlretrieve(url, local, cbk) urllib.urlretrieve(p,'photo/%s.jpg'%p.split('/')[-4]) url要下载的网站 ...

  10. 关于python3.X 报"import urllib.request ImportError: No module named request"错误,解决办法

    #encoding:UTF-8 import urllib.request url = "http://www.baidu.com" data = urllib.request.u ...

随机推荐

  1. java-----基本数据类型包装类

    目的:为了方便操作基本数据类型值,将其封装为对象,在对象定义了属性和行为,丰富了改数据的操作,用于描述该对象的类也就成为基本数据类型对象包装类. 例如:int类型的取值范围:Integer------ ...

  2. sql之表的表达式

    1.派生表 实质:就是特殊的子查询(将查询结果放在from后面) 含有一张Order表: 看下面的sql语句: select orderid,orderdate,custid from ( selec ...

  3. Java发送邮件(带附件)

    实现java发送邮件的过程大体有以下几步: 准备一个properties文件,该文件中存放SMTP服务器地址等参数. 利用properties创建一个Session对象 利用Session创建Mess ...

  4. PAT-乙级-1008. 数组元素循环右移问题 (20)

    1008. 数组元素循环右移问题 (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 一个数组A中存有N(N>0)个整数,在不允 ...

  5. jsp request.getParameterValues获取数组值代码示例

    tt.jsp <form action="tt2.jsp" method="POST"> <select name="two&quo ...

  6. DIY Ruby CPU 分析 Part II

    [编者按]作者 Emil Soman,Rubyist,除此之外竟然同时也是艺术家,吉他手,Garden City RubyConf 组织者.本文是 DIY Ruby CPU Profiling 的第二 ...

  7. HDU 1158 Employment Planning (DP)

    题目链接 题意 : n个月,每个月都至少需要mon[i]个人来工作,然后每次雇佣工人需要给一部分钱,每个人每个月还要给工资,如果解雇人还需要给一笔钱,所以问你主管应该怎么雇佣或解雇工人才能使总花销最小 ...

  8. HDU1429+bfs+状态压缩

    bfs+状态压缩思路:用2进制表示每个钥匙是否已经被找到.. /* bfs+状态压缩 思路:用2进制表示每个钥匙是否已经被找到. */ #include<algorithm> #inclu ...

  9. 首次接触Winform前端交互

    首次接触到在winform中加入网页,且跟前端脚本交互.找了一下这方面的资料 此博文转载原地址为:http://www.cnblogs.com/Charles2008/archive/2009/08/ ...

  10. 华为P6-U06 ROOT

    移动.联通.电信版P6均可成功的EMUI3.0开发版/稳定版 ROOT... - P6/P6s 花粉俱乐部 http://cn.club.vmall.com/forum.php?mod=viewthr ...