Urllib库


python内置的http请求库

1、urllib.request 请求模块

2、urllib.error 异常处理模块(try,catch)

3、urllib.parse url解析模块

4、urllib.robotparser robots.txr解析模块


urlopen

get请求

import urllib.request
reponse=urllib.request.urlopen("http://www.baidu.com")
print(reponse.read().decode('utf-8'))#.read()读请求内容

post请求

import urllib.parse#貌似加不加都行
import urllib.request
data=bytes(urllib.parse.urlencode({'name':'汪国强'}),encoding='utf-8')
response=urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read().decode('utf-8'))

urllib.error

import urllib.request
import socket
import urllib.error
try:
response=urllib.request.urlopen('http://httpbin.org/get',timeout=0.01)
except urllib.error.URLError as e: #超时属于URLError
if isinstance(e.reason,socket.timeout):
print('timeout')

对响应的一些处理

状态码、响应头

import urllib.request
import socket
import urllib.error
response=urllib.request.urlopen('http://www.baidu.com')
print(response.status)
print('-----------------')
print(response.getheaders())
print('-----------------')
print(response.getheader('Server'))

得到:

200        状态码
-----------------

响应头
[('Date', 'Mon, 25 Dec 2017 09:59:01 GMT'), ('Content-Type', 'text/html; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Connection', 'Close'), ('Vary', 'Accept-Encoding'), ('Set-Cookie', 'BAIDUID=C941C9CEBE13F4D6264663E5A10D4603:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'BIDUPSID=C941C9CEBE13F4D6264663E5A10D4603; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'PSTM=1514195941; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'BDSVRTM=0; path=/'), ('Set-Cookie', 'BD_HOME=0; path=/'), ('Set-Cookie', 'H_PS_PSSID=25394_1453_21119_25178_22157; path=/; domain=.baidu.com'), ('P3P', 'CP=" OTI DSP COR IVA OUR IND COM "'), ('Cache-Control', 'private'), ('Cxy_all', 'baidu+e8e6fa769a31bd4f787c267655da18e6'), ('Expires', 'Mon, 25 Dec 2017 09:58:11 GMT'), ('X-Powered-By', 'HPHP'), ('Server', 'BWS/1.1'), ('X-UA-Compatible', 'IE=Edge,chrome=1'), ('BDPAGETYPE', '1'), ('BDQID', '0xc958493100031c89'), ('BDUSERID', '0')]

-----------------

指定的响应头内容

BWS/1.1


如果想在请求时加上请求头怎么办?

import urllib.request
import urllib.parse
head={
"Host": "httpbin.org",
"Upgrade-Insecure-Requests": "",
}
dic={'name':''}
data=bytes(urllib.parse.urlencode(dic),encoding='utf-8')
request=urllib.request.Request('http://httpbin.org/post',data=data,headers=head,method='POST')
response=urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

或者使用request.add_header()

import urllib.request,parser

dic={'name':''}
data=bytes(urllib.parse.urlencode(dic),encoding='utf-8')
request=urllib.request.Request('http://httpbin.org/post',data=data,method='POST')
request.add_header(
"Upgrade-Insecure-Requests", ""
)
response=urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

Handler

代理

使用代理ip

import urllib.request
proxy_handler=urllib.request.ProxyHandler({
'http':'http://116.199.115.78:80/'
})
opener=urllib.request.build_opener(proxy_handler)
response=opener.open('http://httpbin.org/ip')
print(response.read().decode('utf-8'))

urllib(最基本的)库的应用的更多相关文章

  1. Python3 内置http.client,urllib.request及三方库requests发送请求对比

    如有任何学习问题,可以添加作者微信:lockingfree 更多学习资料请加QQ群: 822601020获取 HTTP,GET请求,无参 GET http://httpbin.org/get Pyth ...

  2. requests库和urllib包对比

    python中有多种库可以用来处理http请求,比如python的原生库:urllib包.requests类库.urllib和urllib2是相互独立的模块,python3.0以上把urllib和ur ...

  3. Python使用urllib,urllib3,requests库+beautifulsoup爬取网页

    Python使用urllib/urllib3/requests库+beautifulsoup爬取网页 urllib urllib3 requests 笔者在爬取时遇到的问题 1.结果不全 2.'抓取失 ...

  4. httplib、urllib、urllib2的区别

     Python3.4互联网通讯协议支持 1,webbrowser方便的浏览器容器 2,cgi公共网关接口支持 3,cgitb管理cgi脚本 4,wsgiref  WSGI实体和引用实现 5,urlli ...

  5. [转]Python中urllib与urllib2的区别与联系

    引用文章1:http://my.oschina.net/u/558071/blog/144792 引用文章2:http://zhuoqiang.me/python-urllib2-usage.html ...

  6. Python 学习之urllib模块---用于发送网络请求,获取数据

    1.urllib urllib是Python标准库的一部分,包含urllib.request,urllib.error,urllib.parse,urlli.robotparser四个子模块. (1) ...

  7. urllib、urllib2、urllib3区别和使用

    python3中把urllib和urllib合并为一个库了,urllib对应urllib.request 1.) python 中最早内置拥有的网络请求模块就是 urllib,我们可以看一下 urll ...

  8. python第三方库,你要的这里都有

    Python的第三方库多的超出我的想象. python 第三方模块 转 https://github.com/masterpy/zwpy_lst   Chardet,字符编码探测器,可以自动检测文本. ...

  9. Python 库,资源

    库名称简介 Chardet字符编码探测器,可以自动检测文本.网页.xml的编码. colorama主要用来给文本添加各种颜色,并且非常简单易用. Prettytable主要用于在终端或浏览器端构建格式 ...

随机推荐

  1. SpringCloudLearning

    http://blog.didispace.com/Spring-Boot%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/ https://github.com/forezp ...

  2. PHP模版引擎twig wordpress中调用文章第一张图片

    wordpress当文章没有添加Featured media的时候, 就调用文章第一张图片, 调用的wordpress代码函数为: <?php echo catch_that_image(); ...

  3. 设计模式(一)单例模式:3-静态内部类模式(Holder)

    思想: 相比于懒汉以及饿汉模式,静态内部类模式(一般也被称为 Holder)是许多人推荐的一种单例的实现方式,因为相比懒汉模式,它用更少的代码量达到了延迟加载的目的. 顾名思义,这种模式使用了一个私有 ...

  4. UISearchController,SearchBar的教程-Swift

    如果你的应用程序里显示了大量的数据,滚动的查看大规模的列表会很慢,也会给人一种烦躁的感觉.在这种情况下,查询UISearchController, UISearchBar是极其重要的,可以让用户搜索特 ...

  5. HDU——1393Weird Clock(水题,注意题意)

    Weird Clock Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Tota ...

  6. js方法encodeURI后,关于get请求url长度的限制测试与总结

    (本文仅作个人记录只用比较啰嗦,重点只看红字部分即可) Test.jsp 请求test1.jsp IE11环境下,get请求url最多4096个字节: 请求的是http://localhost:908 ...

  7. 解决 Jackson反序列化 Unexpected token ... , expected VALUE_STRING: need JSON String that contains type id (for subtype of ...)

    首先检查是否是 objectMapper.enableDefaultTyping(); 的受害者.优先考虑删除该配置. 使用Jackson把数组的json字符串反序列化为List时候报了个JsonMa ...

  8. hdu 1558 线段相交+并查集路径压缩

    Segment set Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  9. UVa11762 Race to 1

    期望DP 一个数只能分解成不大于它的数,那么转移构成拓扑关系. 试了一下预处理出不大于x的质数个数,然而程序并没有变快 /*by SilverN*/ #include<algorithm> ...

  10. iis 配置 aspnet起始页

    起始页配置:在default document上面加上路径就可以了,例如 /home/kickoffjob asp.net 关于起始页的一般设置: 1: 在web.config中,加入form认证: ...