urllib模块的使用

2021年2月5日 / 50次阅读 / Last Modified 2021年2月5日

urllib模块来自python的标准库,可以用来抓取网络上的URL资源,本文根据自己的需要,做简要总结。

最简单的case

>>> from urllib.request import urlopen
>>> with urlopen('https://www.pynote.net') as html:
...     page = html.read()
...
>>> len(page)
28204
>>> page[:100]
>>> page[-100:-1]

一个urlopen调用,就下载一个URL资源的内容,无惧https加密协议。

传数据(POST or GET)

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

创建一个Request对象,带上data,这样urllib就会使用POST方法来传数据(有side effect)。

如果自己拼接data到要访问的url上,再用urlopen访问,此时就是GET方法

>>> import urllib.request
>>> import urllib.parse
>>> data = {}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # The order may differ from below.  
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values  # url with data
>>> data = urllib.request.urlopen(full_url)

自定义User-Agent

玩爬虫的人,这个是必须的:

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'  # UA
values = {'name': 'Michael Foord',
          'location': 'Northampton',
          'language': 'Python' }
headers = {'User-Agent': user_agent}

data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

这个case中的Request对象有data,因此是POST方法发送,注意headers参数,UA就在里面。

异常处理

>>> from urllib.request import urlopen
>>> import urllib
>>> import http.server
>>>
>>> try:
...     res = urlopen('https://www.pynote.net/abcde12345')
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(http.server.BaseHTTPRequestHandler.responses[e.code])
...
404
('Not Found', 'Nothing matches the given URI')

正常的http status,通过res.status获得。

http.server.BaseHTTPRequestHandler.responses是一个标准库中的dict对象,预定义了所有的http status对应的解释文字,直接拿来用很方便。

注意还有一些异常,不属于HTTPError类。

获取最终访问的URL

有些URL是重定向,我们通过urlopen返回的response对象,得到真实的最终的URL:

>>> res = urlopen('http://pynote.net')
>>> res.geturl()
'https://www.pynote.net/'

调用返回的response对象的geturl函数,得到真实的URL。

发送HEAD消息

不是所有的URL都需要完整的下载下来处理,比如图片,只要发HEAD消息,确认其能返回200就可以了。基本方法是创建Request对象,在其中指定method:

>>> req = urllib.request.Request('https://www.pynote.net/pics/logo.jpg', method='HEAD')
>>> req.get_method()
'HEAD'
>>> res = urlopen(req)
>>> res.status
200
>>> cont = res.read()
>>> cont
b''

HEAD消息没有内容。

-- EOF --

本文链接:https://www.pynote.net/archives/3446

相关文章

    留言区

    您的电子邮箱地址不会被公开。 必填项已用*标注


    前一篇:
    后一篇:

    More

    麦新杰的Python笔记

    Ctrl+D 收藏本页


    ©Copyright 麦新杰 Since 2019 Python笔记

    go to top