urlopen方法

打开指定的URL

urllib.request.urlopen(url, data=None, [timeout, ]*,
cafile=None, capath=None, cadefault=False, context=None)

url参数,可以是一个string,或者一个Request对象。

data一定是bytes对象,传递给服务器的数据,或者为None。目前只有HTTP requests会使用data,提供data时会是一个post请求,如若没有data,那就是get请求。data在使用前需要使用urllib.parse.urlencode()函数转换成流数据。

from urllib import request

resp=request.urlopen('http://www.baidu.com')
print(type(resp))
#可以看出,urlopen返回的是一个HTTPResponse对象
<class 'http.client.HTTPResponse'>
print(dir(resp))
#resp具有的方法和属性如下,我们最常用的是read和readline
['__abstractmethods__', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_abc_cache', '_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_check_close', '_close_conn', '_get_chunk_left', '_method', '_peek_chunked', '_read1_chunked', '_read_and_discard_trailer', '_read_next_chunk_size', '_read_status', '_readall_chunked', '_readinto_chunked', '_safe_read', '_safe_readinto', 'begin', 'chunk_left', 'chunked', 'close', 'closed', 'code', 'debuglevel', 'detach', 'fileno', 'flush', 'fp', 'getcode', 'getheader', 'getheaders', 'geturl', 'headers', 'info', 'isatty', 'isclosed', 'length', 'msg', 'peek', 'read', 'read1', 'readable', 'readinto', 'readinto1', 'readline', 'readlines', 'reason', 'seek', 'seekable', 'status', 'tell', 'truncate', 'url', 'version', 'will_close', 'writable', 'write', 'writelines']

Request类

URL请求的抽象类。

urllib.request.Request(url, data=None, headers={},
origin_req_host=None, unverifiable=False, method=None)

Example

import urllib.request
with urllib.request.urlopen("http://www.baidu.com") as f:
print(f.read(300))
#最简单的打开一个url的方法
#由于urlopen无法判断数据的encoding,所以返回的是bytes对象。一般会对返回的数据进行decode。
b'<!DOCTYPE html><html lang="zh-cmn-Hans"><head>    <meta charset="UTF-8">    <title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title>    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script></head><body></body></html><script type="text/javascript">var urlNum="96659328_s_ha'
with urllib.request.urlopen("http://www.python.org") as f:
print(f.read(500).decode('utf-8'))
<!doctype html>
<!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie7 lt-ie8 lt-ie9"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8 lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--><html class="no-js" lang="en" dir="ltr"> <!--<![endif]--> <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="prefetch" href="//ajax.googleapis.com/ajax/libs/jqu
#如果想要检索URL资源,并将其保存到一个临时位置,可以使用urlretrieve函数
import urllib.request
local_filename,headers=urllib.request.urlretrieve('http://www.baidu.com')
print(local_filename)
print(headers)
C:\Users\张名昊\AppData\Local\Temp\tmpgvshi0fc
Content-Type: text/html; charset=utf-8
Content-Length: 561
Cache-Control: no-cache
Set-Cookie: jdERAezKGXbgHHHMMBwTrqQ=1;max-age=20;
Connection: close
#urlopen还可以接受Request对象,推荐使用这种方法,因为可以对Request对象进行深度的定制,不仅仅传入一个URL
import urllib.request
req=urllib.request.Request('http://www.baidu.com')
with urllib.request.urlopen(req) as response:
page=response.read(300).decode('utf-8')#我们获取的数据一般是ascii的,decode成utf-8.
print(page)
<!DOCTYPE html><html lang="zh-cmn-Hans"><head>    <meta charset="UTF-8">    <title>百度一下,你就知道</title>    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.8.3/jquery.min.js"></script></head><body></body></html><script type="text/javascript">var urlNum="95855586_s_ha

Data

有时候,我们想想一个URL发送一些数据,一般使用POST请求,不过数据需要encode,然后传递给Request对象。encoding一般由urllib.parse库的函数实现。

import urllib.parse as up
import urllib.request as ur
url='http://www.baidu.com'
values={
'name':'ZhangMinghao',
'location':'Shanghai',
'language':'Python3'
}
data=up.urlencode(values)
data=data.encode('ascii')#data应该是bytes,所以上传给server时需要转换成ascii数据。
req=ur.Request(url,data)
with ur.urlopen(req) as response:
page=response.read()

如果我们不想使用data参数,那么使用GET请求,将data内容与url连接到一起,发送到server。

import urllib.request
import urllib.parse
data={
'name':'ZhangMinghao',
'location':'Shanghai',
'language':'Python3'
}
url_values=urllib.parse.urlencode(data)
print(url_values)
url='http://www.baidu.com'
full_url=url+'?'+url_values
response=urllib.request.urlopen(full_url)
name=ZhangMinghao&location=Shanghai&language=Python3

Headers

有些网页不希望被程序访问,或者向不同的浏览器发送不同的内容。默认的urllib识别为Python-urllib/3.5,可能使server感到疑惑或者返回内容出错。可以通过设置User-Agent来设置我们程序的浏览器识别码,创建Request对象时,出入一个header的字典。

import urllib.parse
import urllib.request url='http://www.baidu.com'
user_agent='Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values={
'name':'ZhangMinghao',
'location':'Shanghai',
'language':'Python3'
}
headers={'User-Agent':user_agent} data=urllib.parse.urlencode(values)
data=data.encode('ascii')
request=urllib.request.Request(url,data,headers)
with urllib.request.urlopen(req) as response:
the_page = response.read()

处理错误

urllib.error模块中包含了相关的各种错误。

URLError,HTTPError等

URLError一般是因为没有网络连接或者server不存在。这种情况下,会产生一个reason属性,是一个tuple,包含了错误码和错误文本

import urllib.error

req=urllib.request.Request('http://www.pretend_server.com')
try: urllib.request.urlopen(req)
except urllib.error.URLError as e:
print(e.reason)
[Errno 11001] getaddrinfo failed

HTTPError

每个http请求都会返回一个状态码,一般处理程序会处理某些状态吗,但是有一些处理不了,就会返回HTTPError,比如404找不到页面,403请求被禁止,401请求授权。不展开讲其他错误码了。

info和geturl

urllib.response模块

geturl返回真正访问的URL地址。

info,返回一个类似字典的对象,来描述获取的对象,尤其是headers。

import urllib.request

resp=urllib.request.urlopen('http://www.baidu.com')
print(resp.info())
Content-Type: text/html; charset=utf-8
Content-Length: 561
Cache-Control: no-cache
Set-Cookie: tSMHvfupnLIgHHHMVijdstJ=1;max-age=20;
Connection: close

还有其他的几个概念,比如授权,代理等,用到的时候再详细讲。

如果您觉得感兴趣的话,可以添加我的微信公众号:一步一步学Python

爬虫入门【1】urllib.request库用法简介的更多相关文章

  1. 爬虫入门【6】Selenium用法简介

    Selenium 是什么? 一句话,自动化测试工具.它支持各种浏览器,包括 Chrome,Safari,Firefox 等主流界面式浏览器. 如果你在这些浏览器里面安装一个 Selenium 的插件, ...

  2. 爬虫入门【3】BeautifulSoup4用法简介

    快速开始使用BeautifulSoup 首先创建一个我们需要解析的html文档,这里采用官方文档里面的内容: html_doc = """ <html>< ...

  3. Python爬虫入门:Urllib parse库使用详解(二)

    文字转载:https://www.jianshu.com/p/e4a9e64082ef,转载内容仅供学习 如有侵权,请联系删除 获取url参数 urlparse 和 parse_qs ParseRes ...

  4. 爬虫入门之urllib库详解(二)

    爬虫入门之urllib库详解(二) 1 urllib模块 urllib模块是一个运用于URL的包 urllib.request用于访问和读取URLS urllib.error包括了所有urllib.r ...

  5. 爬虫——urllib.request库的基本使用

    所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地.在Python中有很多库可以用来抓取网页,我们先学习urllib.request.(在python2.x中为urllib2 ...

  6. Python3 urllib.request库的基本使用

    Python3 urllib.request库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 在Python中有很多库可以用来抓取网页,我们先学习urlli ...

  7. Python爬虫入门之Urllib库的高级用法

    1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...

  8. Python爬虫入门之Urllib库的基本使用

    那么接下来,小伙伴们就一起和我真正迈向我们的爬虫之路吧. 1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解 ...

  9. 爬虫入门之urllib库(一)

    1 爬虫概述 (1)互联网爬虫 一个程序,根据Url进行爬取网页,获取有用信息 (2)核心任务 爬取网页 解析数据 难点 :爬虫和反爬虫之间的博弈 (3)爬虫语言 php 多进程和多线程支持不好 ja ...

随机推荐

  1. 发布android apk,Error running app: No target device found.

    https://developer.android.com/studio/run/device.html\ 一台android设备不识别,android文档还挺全 需要安装usb驱动链接里有

  2. ElasticSearch 监控单个节点详解

    1.介绍 集群健康 就像是光谱的一端——对集群的所有信息进行高度概述. 而 节点统计值 API 则是在另一端.它提供一个让人眼花缭乱的统计数据的数组,包含集群的每一个节点统计值. 节点统计值 提供的统 ...

  3. ssh免密码登录之分发密钥

    ssh免密码登录之分发密钥 1.ssh免密码登录 密码登录和密钥登录有什么不同? 密码登录(口令登录),每次登录都需要发送密码(ssh) 密钥登录,分为公钥和私钥,公钥相当于锁,私钥相当于钥匙 1.1 ...

  4. 10g full join 优化

    今天一个女生咨询我报名学优化.聊着聊着就让我优化一个sql 由于怕泄密,所以删除了 sql . 不好意思 该sql是 olap 的, 在oracle10g 上面跑.跑一次要33秒钟.一般olap报表. ...

  5. Intellij output 中文乱码

    使用intellij有一段时间了,intellij output中文乱码,每次使用这两点解决,就可以解决乱码问题. 1.修改启动参数 修改安装Intellij目录下的C:\Program Files ...

  6. 解决ListView在界面只显示一个item

    ListView只显示一条都是scrollview嵌套listView造成的,将listView的高度设置为固定高度之后,三个条目虽然都完全显示.但是这个地方是动态显示的,不能写死.故采用遍历各个子条 ...

  7. Solidworks如何在装配图中保存单独的一个零件

    如下图所示,我想要保存装配体的一个单独的零部件   选中该零件后点击编辑零部件   然后点击顶部的文件-另存为,弹出"解决模糊情形"对话框,询问你要保存装配体还是零部件   点击确 ...

  8. mother&#39;s day.py 母亲节

    今天母亲节,写了个程序.抓取一个站点的母亲节祝福短信.实现自己主动翻页, 道友们也能够甲乙改造.比方加上节日简洁,time()模块. . . 一起分享吧 # -*- coding: cp936 -*- ...

  9. Codeforces #263 div2 解题报告

    比赛链接:http://codeforces.com/contest/462 这次比赛的时候,刚刚注冊的时候非常想好好的做一下,可是网上喝了个小酒之后.也就迷迷糊糊地看了题目,做了几题.一觉醒来发现r ...

  10. C语言可以给字符数组赋值的方法

    分类: C 2012-04-06 10:23 4081人阅读 评论(0) 收藏 举报 语言c 学了这么多年的C语言,突然发现连字符串赋值都出错,真的很伤心. char a[10]; 怎么给这个数组赋值 ...