from urllib import request
import urllib
import re
from http import cookiejar
#1.爬虫入门程序:调度器,url管理器,下载器,解析器,应用
#定义url
url='http://www.taobao.com'
#定义请求
req=request.Request(url)
#下载页面
resp=request.urlopen(req)#使用的是默认下载器
print(resp.read().decode('utf-8'))
#2.添加请求头
#定义url
url='http://www.taobao.com'
#定义请求头
header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
#定义请求
req=request.Request(url,headers=header)
#下载页面
resp=request.urlopen(req)
print(resp.read().decode('utf-8'))
#3.添加请求数据
#定义url
url='http://www.taobao.com'
#定义请求头
header={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
#添加请求数据
#定义参数(字典类型)
values={'username':'111111','password':'11111111111'}
#参数编码
data=urllib.parse.urlencode(values).encode(encoding='UTF8')
#定义请求
req=request.Request(url,headers=header,data=data)
#下载页面
resp=request.urlopen(req)
print(resp.read().decode('utf-8'))
#4.添加cookie(自定义下载器)
#定义cookie变量
cookie=cookiejar.CookieJar()
#定义cookie处理器
handler=request.HTTPCookieProcessor(cookie)
#定义下载器
opener=request.build_opener(handler)
#下载页面
resp=opener.open(req)
# resp=opener.open('http://www.csdn.com')
print(resp.read().decode('utf-8'))
#opener带cookie,直接用opener去下载页面了
resp2=opener.open('')
#5.异常处理
try:
# 定义url
url = 'http://www.taobao.com'
# 定义请求
req = request.Request(url)
# 下载页面
resp = request.urlopen(req)
except request.URLError as e:
#打印响应码
if hasattr(e,'code'):
print(e.code)
#打印错误原因
if hasattr(e,'reason'):
print(e.reason)
else:
print(resp.read().decode('utf-8'))
#6.动态代理
#设置代理处理器
proxy_handler=request.ProxyHandler({"http":"http://192.168.110.110:8080"})
#构建一个下载器
opener=request.build_opener(proxy_handler)
#打开页面
try:
# resp=opener.open("http://www.zhihu.com",timeout=1)
resp = opener.open(req, timeout=1)
#捕获异常
except request.URLError as e:
if hasattr(e, 'code'):
print(e.code)
if hasattr(e, 'reason'):
print(e.reason)
else:
print(resp.read().decode('utf-8'))
#7.正则表达式
pattern=re.compile(r'abc')
res=re.search(pattern,"absbchcjds")
print(res)