python爬虫笔记之urllib库的简单使用

发送请求

1.urlopen()
请求百度首页:

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
print(type(response))

<class ‘http.client.HTTPResponse’>

response是一个HTTPResponse类型的对象,主要包含read(),readinto(),getheader()(获取响应头的信息)等方法,以及msg,version,status,reason等属性。
利用urlopen(),可以完成基本的简单网页的GET请求抓取。
urlopen()函数的API:
urllib.request.urlopen(url, data=None, [timeout,]*, cafile=None, capath=None, cadefault=Flase, context=None)

  • data参数
    传递参数,并且是字节流编码格式的内容,即bytes类型,使用bytes()方法转换。若设置了此参数,那么请求方式是POST。
    使用http://httpbin.org/post来测试POST请求:
import urllib.request
import urllib.parse

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf-8')
#先使用urlencode()方法将参数字典转化为字符串
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

结果中含有上传的参数{“word”: “hello”}出现在form字段中,这表明是模拟了表单提交的方式,以POST方式传输数据。

  • timeout参数
    timeout参数用于设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间,还没有得到响应,就会抛出异常。若不指定参数,就会使用全局默认时间。
    设置超时时间来控制一个网页如果长时间未响应,就跳过它的抓取,利用try except语句实现:
import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason, socket.timeout):
        print("TIME OUT")

请求超时,捕获异常,打印输出TIME OUT

  • 其他参数
    context用来指定SSL设置
    cafile,capath分别用来指定CA证书和它的路径
    cadefault已弃用,默认False
    2.Request
    urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

  • url必传参数

  • data必须是bytes类型,若是字典先用urllib.parse模块里的urlencode()编码

  • headers请求头,是一个字典,可以通过headers参数直接构造,也可以调用add_header()方法添加

  • origin_req_host是请求方的host名称货IP地址

  • unverifiable默认False,意思是用户没有足够权限来选择接收这个请求的结果

  • method只是请求使用的方法,GET,POST,PUT等
    示例:

from urllib import request, parse

url = 'http://httpbin.org/post'
headers = {
    'User-Agent': 'Mozilla/4.0(compatible;MSIE 5_5; Windows NT)',
    'Host': 'httpbin.org'
}
dict = {
    'name': 'okok'
}
data = bytes(parse.urlencode(dict), encoding='utf-8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

结果

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "name": "okok"
  }, 
  "headers": {
    "Accept-Encoding": "identity", 
    "Content-Length": "9", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Mozilla/4.0(compatible;MSIE 5_5; Windows NT)", 
    "X-Amzn-Trace-Id": "Root=1-5f3b75ac-a3c471f0d4ad918e263bc125"
  }, 
  "json": null, 
  "origin": "180.109.39.75", 
  "url": "http://httpbin.org/post"
}

3.高级用法
Handler,可以用来处理登录验证,处理Cookies, 处理代理设置。利用它们几乎可以做到Http请求中的所有事情。

  • HTTPDefaultErrorHandler:处理HTTP响应错误。
  • HTTPRedirectHandler:处理重定向。
  • HTTPCookiesProcess:处理Cookies。
  • ProxyHandler:用于设置代理。
  • HTTPPasswordMgr:用于管理密码。
  • HTTPBasicAuthHandler:用于管理认证。
  • 验证

有些网站打开说DVD大VDVD大V大V有些网站打开弹出登录界面,验证成功后才能查看页面。使用HTTPBasicAuthHandler,代码如下:

from urllib.request import HTTPPasswordMgrWithDefaultRealm,HTTPBasicAuthHandler,build_opener
from urllib.error import URLError

url = 'http://localhost:5000'
username = '123'
password = '123'

p = HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
auth_handler = HTTPBasicAuthHandler(p)
opener = build_opener(auth_handler)

try:
    reslut = opener.open(url)
    html = reslut.read().decode('utf-8')
    print(html)
except URLError as e:
    print(e.reason)
  • 代理
from urllib.error import URLError
from urllib.request import ProxyHandler, build_opener

proxy_handler = ProxyHandler(
    {
        'http': 'http://127.0.0.1:9743',
        'https': 'https://127.0.0.1:9743'
    }
)
opener = build_opener(proxy_handler)
try:
    response = opener.open('https://www.baidu.com')
    print(response)
except URLError as e:
    print(e.reason)
  • Cookies
import http.cookiejar, urllib.request

cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)

常用方法

  • urlencode()
from urllib.parse import urlencode

params = {
    'name': 'germey',
    'age': 22
}
base_url = 'http://www.baidu.com'
url = base_url + urlencode(params)
print(url)

结果http://www.baidu.comname=germey&age=22

  • quote()
    将内容转化为URL编码格式
from urllib.parse import quote

key = '壁纸'
url = 'http://www.baidu.com/s?wd=' + quote(key)
print(url)

结果http://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8

  • unquote()
    进行URL解码
from urllib.parse import unquote

url = 'http://www.baidu.com/s?wd=%E5%A3%81%E7%BA%B8'
print(unquote(url))

结果http://www.baidu.com/s?wd=壁纸

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值