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. 直方图均衡(HE)与局部色调映射(LTM) .

    直方图均衡(Histogram Equalization)是图像处理中一个十分基础的概念,具有调整图像灰度,增强对比度的作用.    限制对比度自适应直方图均衡(Contrast Limited Ad ...

  2. selenium执行报错:Process refused to die after 10 seconds, and couldn't taskkill it

    十二月 02, 2015 5:16:56 下午 org.openqa.selenium.os.ProcessUtils killWinProcess 警告: Process refused to di ...

  3. 【OpenGL 学习笔记01】HelloWorld演示样例

    <<OpenGL Programming Guide>>这本书是看了忘,忘了又看,赶脚还是把笔记做一做心里比較踏实,哈哈. 我的主题是,好记性不如烂笔头. ========== ...

  4. datatables插件适用示例

    本文共四部分:官网 | 基本使用|遇到的问题|属性表 一:官方网站:[http://www.datatables.NET/] 二:基本使用:[http://www.guoxk.com/node/jQu ...

  5. react-native 扫一扫功能(二维码扫描)功能开发

    1.安装插件 yarn add react-native-smart-barcode 2.关联 react-native link react-native-smart-barcode 3.修改 an ...

  6. SDUTOJ 2804求二叉树的深度

    #include<iostream> #include<stdlib.h> #include<string.h> using namespace std; char ...

  7. IIS管理器如何添加网站

    IIS服务器一些步骤 安装好iis后 右击网站按钮点击添加网站 网站名称填写无所谓,物理路径(注意是大路径,一个项目所有的文件在那个文件夹下), Ip地址自己定义最好是hosts文件已经绑定了域名的, ...

  8. Android布局中 android:layout_gravity="bottom"为何不起作用?

    在android布局时我们有时会需要将位于LinearLayout布局中的控件放在布局底部,或者是同时想将几个控件底部对齐,此时我们自然会想到使用 android:layout_gravity=&qu ...

  9. 在caffe中用训练好的 caffemodel 来分类新的图片所遇到的问题

    结合之前的博客: http://www.cnblogs.com/Allen-rg/p/5834551.html#3949333 用caffemodel去测试单通道的图像(mnist数据集)时,出现了问 ...

  10. 篇章二:[AngularJS] 使用AngularAMD動態載入Service

    前言 「使用AngularAMD動態載入Controller」:這篇文章裡介紹如何使用AngularAMD來動態載入Controller.本篇文章以此為基礎,介紹如何使用AngularAMD來動態載入 ...