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. 【转】How to view word document in WPF application

    How to view word document in WPF application (CSVSTOViewWordInWPF) Introduction The Sample demonstra ...

  2. 1018. Public Bike Management (30)

    时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue There is a public bike service i ...

  3. [Learn Android Studio 汉化教程]第四章 : Refactoring Code

    [Learn Android Studio 汉化教程]第四章 : Refactoring Code 第四章 Refactoring Code    重构代码 在Android Studio中开发,解决 ...

  4. php + mysql + sphinx 的全文检索(2)

    简单 使用php api 去查询 sphinx 的索引数据 $sphinx = new SphinxClient();                 $sphinx->SetServer (  ...

  5. 【BZOJ1030】文本生成器

    Description JSOI交给队员ZYX一个任务,编制一个称之为“文本生成器”的电脑软件:该软件的使用者是一些低幼人群,他们现在使用的是GW文本生成器v6版.该软件可以随机生成一些文章―――总是 ...

  6. [SQL SERVER系列]读书笔记之SQL注入漏洞和SQL调优

    最近读了程序员的SQL金典这本书,觉得里面的SQL注入漏洞和SQL调优总结得不错,下面简单讨论下SQL注入漏洞和SQL调优. 1. SQL注入漏洞 由于“'1'='1'”这个表达式永远返回 true, ...

  7. ssh scp访问ipv6地址

    从这里学来的.http://blog.mattandanne.org/2012/01/sftpscp-and-ipv6-link-local-addresses.html当采用ipv6的地址去连接另外 ...

  8. ionicPopup确认对话框

    $ionicPopup.confirm({ title: $rootScope.app_name, template: 'Do you want to add this to database?', ...

  9. [转载]test后跟je

    今天俺也用OD(OllyDbg)反汇编了个小软件,其中里面有下面两条指令: 没太明白什么意思,google一下,在看雪论坛上发现了一个大虾的解释很详细,记录一下: 1.test a,b 是a与b相与的 ...

  10. Side by Side Assembly介绍--manifest文件的使用

    什么是Side-by-Side Assembly? Side-by-Side Assembly(建称SxS)是微软在Visual Studio 2005(Windows 2000?)中引入的技术,用来 ...