爬虫基础php
1.爬虫:请求网站并请求数据的自动化程序。html
2.爬虫的基本流程:python
1.发起请求正则表达式
经过http库向目标站点发起请求,即发送一个request,请求包含额外的headers信息,等待服务器响应。数据库
2.解析内容json
获得内容是HTML,能够用正则表达式、网页解析库进行解析。多是json,多是二进制,能够作进一步处理服务器
3.获取响应内容cookie
若是服务器正常响应会获得一个response页面内容,类型多是json字符串、二进制数据、HTML等。网络
4.保存数据socket
能够保存为文本,或者数据库,特定格式。
2.urllib基本用法
官方文档地址:https://docs.python.org/3/library/urllib.html
Urllib是python内置的HTTP请求库
包括如下模块
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块
关于urllib.request.urlopen参数的介绍:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
url参数的使用
urlopen通常经常使用的有三个参数,它的参数以下:
urllib.requeset.urlopen(url,data,timeout)
response.read()能够获取到网页的内容,若是没有read()
data参数的使用
这里就用到urllib.parse,经过bytes(urllib.parse.urlencode())能够将post数据进行转换放到urllib.request.urlopen的data参数中。这样就完成了一次post请求。
因此若是咱们添加data参数的时候就是以post请求方式请求,若是没有data参数就是get请求方式
import urllib.request
import urllib.parse
data=bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
print(data)
response=urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
timeout参数的使用
在某些网络状况很差或者服务器端异常的状况会出现请求慢的状况,或者请求异常,因此这个时候咱们须要给
请求设置一个超时时间,而不是让程序一直在等待结果。例子以下:
import urllib.request
response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())
import urllib.request
import urllib.error
import socket
try:
response=urllib.request.urlopen('http://httpbin.org/get', timeout=1)
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print(''TIME OUT'')
3.设置Headers
有不少网站为了防止程序爬虫爬网站形成网站瘫痪,会须要携带一些headers头部信息才能访问,最长见的有user-agent参数,使用urllib.request
#添加请求头
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': 'zhaofan'
}
data=bytes(parse.urlencode(dict),encoding='utf8')
req=request.Request(url=url,data=data,headers=headers,method='POST')
response=request.urlopen(req)
print(response.read().decode('utf-8'))
#第二种添加头部信息方式
from urllib import request, parse
url = 'http://httpbin.org/post'
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
response = request.urlopen(req)
4.高级用法各类handler
代理,ProxyHandler
经过rulllib.request.ProxyHandler()能够设置代理,网站它会检测某一段时间某个IP 的访问次数,若是访问次数过多,它会禁止你的访问,因此这个时候须要经过设置代理来爬取数据
import urllib.request
proxy_handler = urllib.request.ProxyHandler({
'http':'112.35.29.53:8088',
'https':'165.227.169.12:80'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())
5.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)
同时cookie能够写入到文件中保存,有两种方式http.cookiejar.MozillaCookieJar和http.cookiejar.LWPCookieJar()。
具体代码例子以下:
http.cookiejar.MozillaCookieJar()方式
import http.cookiejar, urllib.request
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(filename)
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)
http.cookiejar.LWPCookieJar()方式
import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
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获取的话能够经过load方式,固然用哪一种方式写入的,就用哪一种方式读取。
import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
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'))
在不少时候咱们经过程序访问页面的时候,有的页面可能会出现错误,相似404,500等错误
这个时候就须要咱们捕捉异常,
from urllib import request,error
try:
response = request.urlopen("http://pythonsite.com/1111.html")except error.URLError as e:
print(e.reason)
上述代码访问的是一个不存在的页面,经过捕捉异常,咱们能够打印异常错误
这里咱们须要知道的是在urllb异常这里有两个个异常错误:
URLError,HTTPError,HTTPError是URLError的子类
URLError里只有一个属性:reason,即抓异常的时候只能打印错误信息,相似上面的例子
HTTPError里有三个属性:code,reason,headers,即抓异常的时候能够得到code,reson,headers三个信息,例子以下:
from urllib import request,errortry:
response = request.urlopen("http://pythonsite.com/1111.html")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")
同时,e.reason其实也能够在作深刻的判断,例子以下:
import socket
from urllib import error,request
try:
response = request.urlopen("http://www.pythonsite.com/",timeout=0.001)except error.URLError as e:
print(type(e.reason))
if isinstance(e.reason,socket.timeout):
print("time out")
urlparse
The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.
urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
功能一:
from urllib.parse import urlparse
result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")print(result)
结果为:
这里就是能够对你传入的url地址进行拆分
同时咱们是能够指定协议类型:
result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
这样拆分的时候协议类型部分就会是你指定的部分,固然若是你的url里面已经带了协议,你再经过scheme指定的协议就不会生效
urlunpars
其实功能和urlparse的功能相反,它是用于拼接,例子以下:
from urllib.parse import urlunparse
data = ['http','www.baidu.com','index.html','user','a=123','commit']print(urlunparse(data))
结果以下
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'))
结果为:
从拼接的结果咱们能够看出,拼接的时候后面的优先级高于前面的url
urlencode
这个方法能够将字典转换为url参数,例子以下
from urllib.parse import urlencode
params = {
"name":"zhaofan",
"age":23,
}
base_url = "http://www.baidu.com?"
url = base_url+urlencode(params)print(url)
结果为: