1.爬虫
# 1. 爬虫?
http://www.baidu.com, (图片, url, 视频, 文件)
# 2. 浏览网页时经历的过程
浏览器 (请求request)-> 输入URL地址(http://www.baidu.com/index.html file:///mnt ftp://172.25.254.250/pub
-> http协议确定, www.baidu.com访问的域名确定 -> DNS服务器解析到IP地址
-> 确定要访问的网页内容 -> 将获取到的页面内容返回给浏览器(响应过程)
)
# 3. 爬取网页
1). 基本方法
from urllib import request
from urllib.error import URLError
try:
respose = request.urlopen('http://www.baidu.com', timeout=10)
content = respose.read().decode('utf-8')
print(content)
except URLError as e:
print("访问超时", e.reason)
2). 使用Request对象(可以添加其他的头部信息)
from urllib import request
from urllib.error import URLError
url = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html'
headers = {'User-Agent':'http://www.cbrc.gov.cn/chinese/jrjg/index.html'}
try:
# 实例化request对象, 可以自定义请求的头部信息;
req = request.Request(url, headers=headers)
# urlopen不仅可以传递url地址, 也可以传递request对象;
content = request.urlopen(req).read().decode('utf-8')
print(content)
except URLError as e:
print("连接失败",e.reason)
else:
print("连接成功")
3).后续添加头部信息
from urllib import request
from urllib.error import URLError
url = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html'
user_agent = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html'
try:
# 实例化request对象, 可以自定义请求的头部信息;
req = request.Request(url)
req.add_header('User-Agent',user_agent)
# urlopen不仅可以传递url地址, 也可以传递request对象;
content = request.urlopen(req).read().decode('utf-8')
print(content)
except URLError as e:
print(e.reason)
else:
print("success")
#4. 反爬虫策略
1). 模拟浏览器(同上)
1.Android
Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19
Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Mozilla/5.0 (Linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
2.Firefox
Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0
3.Google Chrome
Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36
Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19
4.iOS
Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3
2.IP代理
当抓取网站时, 程序的运行速度很快, 如果通过爬虫去访问, 一个固定的ip访问频率很高,网站如果做反爬虫策略, 那么就会封掉ip;
如何解决?
- 设置延迟;time.sleep(random.randint(1,5))
- 使用IP代理, 让其他IP代替你的IP访问;
如何获取代理IP?
http://www.xicidaili.com/
如何实现步骤?
1). 调用urllib.request.ProxyHandler(proxies=None); --- 类似理解为Request对象
2). 调用Opener--- 类似与urlopen, 这个是定制的
3). 安装Opener
4). 代理IP的选择
from urllib import request
from urllib.error import URLError
url = 'https://www.whatismyip.com/'
proxy = {'https':'171.221.239.11:808', 'http':'218.14.115.211:3128'}
user_agent = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html'
# 1).调用urllib.request.ProxyHandler(proxies=None); --- 类似理解为Request对象
proxy_support = request.ProxyHandler(proxy)
# 2).调用Opener - -- 类似与urlopen, 这个是定制的
opener = request.build_opener(proxy_support)
# 伪装浏览器
opener.addheaders = [('User-Agent',user_agent)]
# 3).安装Opener
request.install_opener(opener)
# 4).代理IP的选择
response = request.urlopen(url)
content = response.read().decode('utf-8')
print(content)
3.保存cookie信息
# cookie信息是什么?
cookie, 某些网站为了辨别用户身份, 只有登陆之后才能访问某个页面;
进行一个会话跟踪, 将用户的相关信息包括用户名等保存到本地终端
a).实现步骤
from http import cookiejar
from urllib.request import HTTPCookieProcessor
from urllib import request
# 1. 如何将Cookie保存到变量中, 或者文件中;
# 1). 声明一个CookieJar ---> FileCookieJar --> MozillaCookie
cookie = cookiejar.CookieJar()
# 2). 利用urllib.request的HTTPCookieProcessor创建一个cookie处理器
handler = HTTPCookieProcessor(cookie)
# 3). 通过CookieHandler创建opener
# 默认使用的openr就是urlopen;
opener = request.build_opener(handler)
# 4). 打开url页面
response = opener.open('http://www.baidu.com')
# 5). 打印该页面的cookie信息
print(cookie)
for item in cookie:
print(item)
b).如何将Cookie以指定格式保存到文件中
from http import cookiejar
from urllib.request import HTTPCookieProcessor
from urllib import request
# 1). 设置保存cookie的文件名
cookieFilename = 'cookie.txt'
# 2). 声明一个MozillaCookie,用来保存cookie并且可以写入文件内
cookie = cookiejar.MozillaCookieJar(filename=cookieFilename)
# 3). 利用urllib.request的HTTPCookieProcessor创建一个cookie处理器
handler = HTTPCookieProcessor(cookie)
# 4). 通过CookieHandler创建opener
# 默认使用的openr就是urlopen;
opener = request.build_opener(handler)
# 5). 打开url页面
response = opener.open('http://www.baidu.com')
# 6). 打印cookie,
print(cookie)
print(type(cookie))
# ignore_discard, 即使cookie信息将要被丢弃。 也要把它保存到文件中;
# ignore_expires, 如果在文件中的cookie已经存在, 就覆盖原文件写入;
cookie.save(ignore_discard=True, ignore_expires=True)
c).从文件中获取cookie并访问
from http import cookiejar
from urllib import request
from urllib.request import HTTPCookieProcessor
# 1). 指定cookie文件存在的位置
cookieFilename = 'cookie.txt'
# 2).声明一个MozillaCookie,用来保存cookie并且可以写入文件, 用来读取文件中的cookie信息
cookie = cookiejar.MozillaCookieJar()
# 3). 从文件中读取cookie内容
cookie.load(filename=cookieFilename)
# 4). 利用urllib.request的HTTPCookieProcessor创建一个cookie处理器
handler = HTTPCookieProcessor(cookie)
# 5). 通过CookieHandler创建opener
# 默认使用的openr就是urlopen;
opener = request.build_opener(handler)
# 6). 打开url页面
response = opener.open('http://www.baidu.com')
#7). 打印信息
print(response.read().decode('utf-8'))
4. urllib常见异常处理
from urllib import request, error
#
try:
url = 'https://www.csdn.net/hello.html'
response = request.urlopen(url)
print(response.read().decode('utf-8'))
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
print("成功")
from urllib import request, error
#
try:
url = 'https://www.baidu.com/hello.html'
response = request.urlopen(url)
print(response.read().decode('utf-8'))
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
print("成功")
扫描二维码关注公众号,回复:
4753686 查看本文章
# 超时异常处理
from urllib import request, error
import socket
#
try:
url = 'https://www.baidu.com'
response = request.urlopen(url, timeout=0.01)
print(response.read().decode('utf-8'))
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
if isinstance(e.reason, socket.timeout):
print("超时")
else:
print("成功")
5.url解析
# 1.urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
# - 功能: 将url分为6部分, 返回一个元组;
# 协议, 服务器的地址(ip:port), 文件路径, 访问的页面
from urllib import parse
# url = 'http://www.google.com/search?hl=en&q=urlparse&btnG=Google+Search'
url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=hello&rsv_pq=d0f841b10001fab6&rsv_t=2d43603JgfgVkvPtTiNX%2FIYssE6lWfmSKxVCtgi0Ix5w1mnjks2eEMG%2F0Gw&rqlang=cn&rsv_enter=1&rsv_sug3=6&rsv_sug1=4&rsv_sug7=101&rsv_sug2=0&inputT=838&rsv_sug4=1460'
parsed_tuple = parse.urlparse(url)
print(parsed_tuple)
print(parsed_tuple.netloc)
print(parsed_tuple.path)
# urllib.parse.urlunparse(parts)¶
print(parse.urlunparse(parsed_tuple))
# urlencode
将字符串以URL编码 返回值:字符串 函数种类:编码处理 函数将字符串以URL 编码
from urllib.parse import urlencode
params = {
'name':'westos',
'age':20
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)
6.requests模块
Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。
import requests
url = 'http://www.baidu.com'
response = requests.get(url)
print(response)
print(response.status_code)
print(response.cookies)
print(response.text)
print(type(response.text))