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. ios开发中APP底部上滑不能调出如WiFi、蓝牙、播放等的设置页面的解决的方法

    在开发的APP中我们通常通过手动底部上滑来调出WiFi.蓝牙.飞行模式等的设置页面.有时我们开发的APP无法调出. 解决的方法: 进入iPhone "设置" --> &quo ...

  2. MySQL增加访问ip

    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '123456' WITH GRANT OPTION; flush privileges;

  3. KodExplorer介绍

    KodExplorer介绍 KOD·简介 官方网站https://kodcloud.com/ KodExplorer可道云,原名芒果云,是一款基于 PHP 开发的开源 WEB 网页版轻量级私有云和在线 ...

  4. 系统重装 U盘安装XP操作系统开机出现提示txtsetup.sif怎么办

    你的这个问题 是安装xp时把xp做成u盘出现的 原因是xp没有在根本上支持这种安装 到win7后才支持的 解决方法有以下几种 1,刻录成cd 2重新下载xp ghost版的不会出现这个问题 3证实Ul ...

  5. 使用 mybatis + flying-0.9.4 的电商后端

    代码地址如下:http://www.demodashi.com/demo/12779.html mybatis.flying - 阳春 (Sunny-Spring) 项目介绍请见 flying-doc ...

  6. preloadjs实现网页资源预加载

    <!doctype html> <html lang="zh"> <head> <title>PreloadJS的基础使用</ ...

  7. php-fpm添加service服务

    原文:http://blog.csdn.net/whatday/article/details/50659992 php-fpm在5.3.2版本以后不支持service php-fpm start等命 ...

  8. MQTT--topic

    1.topic  定阅与发布必须要有主题,只有当定阅了某个主题后,才能收到相应主题的payload,才能进行通信. 2. 主题层级分隔符—“/”  主题层级分隔符使得主题名结构化.如果存在分隔符,它将 ...

  9. BGP双线的真真假假

    BGP双线的真真假假: 国内不少IDC服务商都号称自己是“真正的双线”.“双线单IP”.“全路由双线”,但是,这其中有没有水分?他们都是BGP双线?BGP的门槛真的这么低吗? 首先,要构建真正的BGP ...

  10. PAT 1001. A+B Format(水题)

    #include<cstdio> #include<cstring> using namespace std; char s[10]; int main() { int a,b ...