您的位置:首页 > 编程语言 > Python开发

python3 爬虫入门(一)urlib库基本使用

2017-11-21 14:22 441 查看
1.什么是urlib?

Urllib是python内置的HTTP请求库
包括以下模块
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块

2.关于urllib.request.urlopen参数的介绍:
urlopen一般常用的有三个参数,它的参数如下:
urllib.requeset.urlopen(url,data,timeout)
response.read()可以获取到网页的内容

例:通过请求百度的get请求获得百度
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')

例:通过bytes(urllib.parse.urlencode())可以将post数据进行转换放到urllib.request.urlopen的data参数中,这样就完成了一次post请求
import urllib.parse

import urllib.request

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')

print(data)

response = urllib.request.urlopen('http://httpbin.org/post', data=data)

print(response.read())

3.timeout参数的使用

在某些网络情况不好或者服务器端异常的情况会出现请求慢的情况,或者请求异常,所以这个时候我们需要给

请求设置一个超时时间,而不是让程序一直在等待结果。例子如下:

import urllib.request

response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)

print(response.read())

4.响应类型
import urllib.request

response = urllib.request.urlopen('https://www.python.org')

print(type(response))

5.响应头
设置Headers:有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访问,最长见的有user-agent参数
import urllib.request

request = urllib.request.Request('https://python.org')

response = urllib.request.urlopen(request)

print(response.read().decode('utf-8'))

6.代理,ProxyHandler
通过rulllib.request.ProxyHandler()可以设置代理,网站它会检测某一段时间某个IP
的访问次数,如果访问次数过多,它会禁止你的访问,所以这个时候需要通过设置代理来爬取数据

import urllib.request

proxy_handler = urllib.request.ProxyHandler({

    'http': 'http://127.0.0.1:9743',

    'https': 'https://127.0.0.1:9743'

})

opener = urllib.request.build_opener(proxy_handler)

response = opener.open('http://www.baidu.com')

print(response.read())

7.cookie,HTTPCookiProcessor
cookie中保存中我们常见的登录信息,有时候爬取网站需要携带cookie信息访问,这里用到了http.cookijar,用于获取cookie以及存储cookie

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)

8.异常处理
urllb异常:URLError,HTTPError(HTTPError是URLError的子类)
URLError里只有一个属性:reason,即抓异常的时候只能打印错误信息
HTTPError里有三个属性:code,reason,headers,即抓异常的时候可以获得code,reason,headers三个信息,例子如下:
from urllib import request,error

try:

    response = request.urlopen("http://ww.baidu.com")

except error.HTTPError as e:

    print(e.reason)

    print(e.code)

    print(e.headers)

except error.URLError as e:

    print(e.reason)

else:

    print("reqeust successfully")

9.URL解析urlparse:URL解析函数的重点是将URL字符串拆分到其组件中,或将URL组件组合到URL字符串中。
from urllib.parse import urlparse

result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")

print(result)

10.urlunpars:功能和urlparse的功能相反,它是用于拼接,例子如下:
from urllib.parse import urlunparse

data = ['http','www.baidu.com','index.html','user','a=123','commit']

print(urlunparse(data))

11.urljoin:做拼接的,例子如下:
from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'FAQ.html'))

print(urljoin('http://www.baidu.com', 'https://pythonsite.com/FAQ.html'))

print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html'))

print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html?question=2'))

print(urljoin('http://www.baidu.com?wd=abc', 'https://pythonsite.com/index.php'))

print(urljoin('http://www.baidu.com', '?category=2#comment'))

print(urljoin('www.baidu.com', '?category=2#comment'))

print(urljoin('www.baidu.com#comment', '?category=2'))

12.最基本的抓站

from urllib import request    

response = request.urlopen("http://www.baidu.com/")  

content = response.read().decode('utf-8')  

print(content) 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: