urllib库的使用



urllib库是python内置的http请求库

四个模块
  1. urllib.request :请求模块

  2. urllib.error: 异常处理模块

  3. urllib.parse : url解析模块

    工具模块, 提供了很多处理方法:拆分、合并...

  4. urllib.robotparser : robots.txt解析模块(用的不是很多)

    判断哪些网站是可以爬的那些不可以

关于导包

python2中:

import urllib2
urllib2.urlopen(url)

python3中:

import urllib.request
urllib.request.urlopen(url)
使用

get方式获取数据:

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read())

post方式获取:需要传data参数、headers

将cookie信息存到本地:
import http.cookiejar, urllib.request
cookie = http.cookiejar.MozillaCookieJar('cookie.txt')
# 也可以把Mozilla改成LWP
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)

打开当前路径下的cookie.txt,发现都记录下来了。

将存的cookie读取出来
import http.cookiejar, urllib.request

cookie = http.cookiejar.MozillaCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

这样,在请求网页的时候,会自动把读取出来的cookie传进请求里面, 维持一个登录状态。

异常处理
  • e.reason 打印异常原因
try:
    response = request.urlopen('http://www.baidu.com')
except error.HTTPError as e:
    print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
    print(e.reason)
else:
    print('请求成功')
URL解析(工具模块)
urlparse
from urllib.parse import urlparse

result = urlparse('https://www.baidu.com/home/news/data/newspage?nid=15382671805503563942&n_type=0&p_from=1')
print(type(result),result)

输出结果:

<class 'urllib.parse.ParseResult'> 
ParseResult(
    scheme='https',
    netloc='www.baidu.com', path='/home/news/data/newspage', 
    params='', 
    query='nid=15382671805503563942&n_type=0&p_from=1',
    fragment=''
)
urlunparse

传入一个数组,自动拼接成url

from urllib.parse import urlunparse
# 注意参数个数
data = ['http', 'www.weibo.com', 'index.html','user', 'a=7','fragment']
print(urlunparse(data))
urljoin 拼接url
urlencode

把一个字典对象,转换成get请求参数

from urllib.parse import urlencode

params = {
    'name': 'dimples',
    'age': 24
}
base_url = 'http://www.weibo.com?'
url = base_url + urlencode(params)
print(url)



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值