1.基本方法

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  需要打开的网址

-         data:Post提交的数据

-         timeout:设置网站的访问超时时间

直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。

1 from urllib import request
2 response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
3 page = response.read()
4 page = page.decode('utf-8')

urlopen返回对象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作

-         info():返回HTTPMessage对象,表示远程服务器返回的头信息

-         getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到

-         geturl():返回请求的url

2.使用Request

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

使用request()来包装请求,再通过urlopen()获取页面。

urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html
 1 url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
 2 headers = {
 3     'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
 4                   r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
 5     'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
 6     'Connection': 'keep-alive'
 7 }
 8 req = request.Request(url, headers=headers)
 9 page = request.urlopen(req).read()
10 page = page.decode('utf-8')
urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html

用来包装头部的数据:

-         User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言

-         Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的

-         Connection:表示连接状态,记录Session的状态。

3.Post数据

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post。

urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html
 1 from urllib import request, parse
 2 url = r'http://www.lagou.com/jobs/positionAjax.json?'
 3 headers = {
 4     'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
 5                   r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
 6     'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
 7     'Connection': 'keep-alive'
 8 }
 9 data = {
10     'first': 'true',
11     'pn': 1,
12     'kd': 'Python'
13 }
14 data = parse.urlencode(data).encode('utf-8')
15 req = request.Request(url, headers=headers, data=data)
16 page = request.urlopen(req).read()
17 page = page.decode('utf-8')
urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)

urlencode()主要作用就是将url附上要提交的数据。 

urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html
1 data = {
2     'first': 'true',
3     'pn': 1,
4     'kd': 'Python'
5 }
6 data = parse.urlencode(data).encode('utf-8')
urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html

经过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的数据必须是bytes或者iterable of bytes,不能是str,因此需要进行encode()编码

1 page = request.urlopen(req, data=data).read()

当然,也可以把data的数据封装在urlopen()参数中

4.异常处理

urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html
 1 def get_page(url):
 2     headers = {
 3         'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
 4                     r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
 5         'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
 6         'Connection': 'keep-alive'
 7     }
 8     data = {
 9         'first': 'true',
10         'pn': 1,
11         'kd': 'Python'
12     }
13     data = parse.urlencode(data).encode('utf-8')
14     req = request.Request(url, headers=headers)
15     try:
16         page = request.urlopen(req, data=data).read()
17         page = page.decode('utf-8')
18     except error.HTTPError as e:
19         print(e.code())
20         print(e.read().decode('utf-8'))
21     return page
urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html

5、使用代理 

urllib.request.ProxyHandler(proxies=None)

当需要抓取的网站设置了访问限制,这时就需要用到代理来抓取数据。

urllib 模块    https://www.cnblogs.com/guishou/articles/7089496.html
 1 data = {
 2         'first': 'true',
 3         'pn': 1,
 4         'kd': 'Python'
 5     }
 6 proxy = request.ProxyHandler({'http': '5.22.195.215:80'})  # 设置proxy
 7 opener = request.build_opener(proxy)  # 挂载opener
 8 request.install_opener(opener)  # 安装opener
 9 data = parse.urlencode(data).encode('utf-8')
10 page = opener.open(url, data).read()
11 page = page.decode('utf-8')
12 return page


1.URLError

首先解释下URLError可能产生的原因:

  • 网络无连接,即本机无法上网
  • 连接不到特定的服务器
  • 服务器不存在

在代码中,我们需要用try-except语句来包围并捕获相应的异常。下面是一个例子,先感受下它的风骚

 

 
 
1
2
3
4
5
6
7
urllib2
 
)
:
)
:
reason

 

我们利用了 urlopen方法访问了一个不存在的网址,运行结果如下:

 

 
 
1
failed

 

它说明了错误代号是11004,错误原因是 getaddrinfo failed

2.HTTPError

HTTPError是URLError的子类,在你利用urlopen方法发出一个请求时,服务器上都会对应一个应答对象response,其中它包含一个数字”状态码”。举个例子,假如response是一个”重定向”,需定位到别的地址获取文档,urllib2将对此进行处理。

其他不能处理的,urlopen会产生一个HTTPError,对应相应的状态吗,HTTP状态码表示HTTP协议所返回的响应的状态。

 

 


通过Python所带的urlparse模块,我们能够轻松地把URL分解成元件,之后,还能将这些元件重新组装成一个URL。当我们处理HTML 文档的时候,这项功能是非常方便的。

1.1 urlparse.urlparse 函数

此函数会将一个url字符串分解为6个元素,以元祖的形式返回。有的元素可能为空,例:

  • >>> from urlparse import urlparse
  • >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
  • >>> o 
  • ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
  •             params='', query='', fragment='')
  • >>> o.scheme
  • 'http'
  • >>> o.port
  • 80
  • >>> o.geturl()
  • 'http://www.cwi.nl:80/%7Eguido/Python.html'
  • 详细的返回值信息:

    Attribute Index Value Value if not present
    scheme 0 URL scheme specifier empty string
    netloc 1 Network location part empty string
    path 2 Hierarchical path empty string
    params 3 Parameters for last path element empty string
    query 4 Query component empty string
    fragment 5 Fragment identifier empty string
    username   User name None
    password   Password None
    hostname   Host name (lower case) None
    port   Port number as integer, if present None

    需要注意的是,传入的URL开头必须要有双斜杠//,否则会被认为是相对路径

    1.2 urlparse.urlunparse 函数

    此函数作用是把urlparse()分解的元素再拼合还原为一个url,它接收元组(scheme, netloc, path, parameters, query, fragment)后,会重新组成一个具有正确格式的URL,以便供Python的其他HTML解析模块使用。

    1.3 urlparse.urlsplit 函数

    类似urlparse 函数,不过它的返回列表里面不高括params

    1.4 urlparse.urlunsplit 函数

    和urlparse.urlsplit 对应,合成URL

    1.5 urlparse.urljoin 函数

    作用是将一个url替换为另一个url,例:

  • >>> from urlparse import urljoin
  • >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
  • 'http://www.cwi.nl/%7Eguido/FAQ.html'
  •  

    2. 获取html页面模块urllib


    Python所带的urllib和urllib2这两个模块为我们提供了从URL打开并获取数据的功能。

    若要通过urllib模块中的urlopen(url [,data])函数打开一个HTML文档,必须提供该文档的URL地址,包括文件名。函数urlopen不仅可以打开位于远程web服务器上的文件,而 且可以打开一个本地文件,并返回一个类似文件的对象,我们可以通过该对象从HTML文档中读出数据。 
     
    一旦打开了HTML文档,我们就可以像使用常规文件一样使用read([nbytes])、readline()和readlines()函数来对文件进行读操作。若要读取整个HTML文档的内容的话,您可以使用read()函数,该函数将文件内容作为字符串返回。

    打开一个地址之后,您可以使用geturl()函数取得被获取网页的真正的URL。这是很有用的,因为urlopen(或使用的opener对象)也许会伴随一个重定向。获取的网页URL也许和要求的网页URL不一样。

    另一个常用的函数是位于从urlopen返回的类文件对象中的info()函数,这个函数可以返回URL位置有关的元数据,比如内容长度、内容类型,等等。

  • import urllib2
  • def get_html(url):
  •     html = urllib2.urlopen(url).read()
  •     return html
  •  

    2.1 POST方式请求页面

  • import urllib2, urllib
  • data = {'name' : 'www', 'password' : '123456'} # or [('name','www'),('password','123456'),('item',1),('item',2)] 重复字段
  • f = urllib2.urlopen(
  •         url = 'http://www.ideawu.net/',
  •         data = urllib.urlencode(data)
  •         )
  • print f.read()
  • 2.2 使用Cookie的情况

  • import urllib2
  • cookies = urllib2.HTTPCookieProcessor()
  • opener = urllib2.build_opener(cookies)
  • f = opener.open('http://www.ideawu.net/?act=login&name=user01')
  • data = 'Hello'
  • request = urllib2.Request(
  •         url = 'http://www.ideawu.net/?act=send',
  •         headers = {'Content-Type' : 'text/xml'},
  •         data = data)
  • opener.open(request)
  • 第一次 open() 是进行登录. 服务器返回的 Cookie 被自动保存在 cookies 中, 被用在后来的请求.
    第二次 open() 用 POST 方法向服务器发送了 Content-Type=text/xml 的数据. 如果你不创建一个 Request, 而是直接使用 urlopen() 方法, Python 强制把 Content-Type 改为 application/x-www-form-urlencoded.

    相关文章:

    • 2022-12-23
    • 2022-12-23
    • 2022-01-08
    • 2022-12-23
    • 2022-12-23
    • 2022-12-23
    • 2021-08-01
    • 2021-08-14
    猜你喜欢
    • 2021-06-21
    • 2022-01-07
    • 2021-06-06
    • 2021-11-21
    • 2021-09-10
    • 2022-02-24
    • 2021-06-26
    相关资源
    相似解决方案