Python爬虫基础

HTTP超文本传输协议,服务器端口80;HTTPS是HTTP的加密版本,在HTTP加入ssh,服务器端口443

url,统一资源定位符

scheme://host:port/path/?query-striing=xxx#anchor
scheme:代表的是访问的协议,一般为http或者https以及ftp等。
host:主机名,域名,比如www.baidu.com
port:端口号。当你访问一个网站的时候,浏览器默认使用80端口。
path:查找路径。比如:www.jianshu.com/trending/now,后面的trending/now就是path。
query-string:查询字符串,比如:www.baidu.com/s?wd=python,后面的wd=python就是查询字符串。
anchor:锚点,后台一般不用管,前端用来做页面定位的。

解析网址

from urllib import parse
url = 'https://www.baidu.com/s?wd=ghfgd&rsv_spt=1&rsv_iqid=0xd3ebcc130003eb17&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=0&rsv_sug3=6&rsv_sug1=1&rsv_sug7=100&inputT=1390&rsv_sug4=1454'

result = parse.urlparse(url)
print('scheme:',result.scheme)
print('netloc:',result.netloc)
print('path:',result.path)
print('query:',result.query)

cookie的格式:

Set-Cookie: NAME=VALUE;Expires/Max-age=DATE;Path=PATH;Domain=DOMAIN_NAME;SECURE

参数意义:
NAME:cookie的名字。
VALUE:cookie的值。
Expires:cookie的过期时间。
Path:cookie作用的路径。
Domain:cookie作用的域名。
SECURE:是否只在https协议下起作用。

urlretrieve下载函数

这个函数可以方便的将网页上的一个文件保存到本地

from urllib import request
request.urlretrieve('url','保存地址')

urllib的代理访问

url = ''
proxy = {'http':'120.194.18.90:81'}
创建Handler
Handler = request.Proxyhandler(proxy)
创建opener
opener = request.bulid_pener(handler)
安装opener
requset.install_opener(opener)
try:
	rsp = request.urlopen(url)
	html = rsp.read().decode()
except error.URLError as e:
	print(e)

urllib的cookie保持登录状态

from urllib import request,parse
import ssl
#忽略安全问题
ssl._create_default_https_context = ssl._create_unverified_context
from http import cookiejar
#声明一个CookieJar对象实例来保存cookie
cookie = cookiejar.CookieJar()
#利用urllib库的HTTPCookieProcessor对象来创建cookie处理器
handler = request.HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = request.build_opener(handler)
login_url = ''
data = {}
# 对post的data内容进行编码,encode后才变为bytes
data = parse.urlencode(data).encode()
# http协议的请求头
headers = {}
# 构造请求Request对象
req = request.Request(login_url, data=data, headers=headers)
rsp = opener.open(req)
html = rsp.read().decode()
此时cookie已经保存,使用opener。open打开base_url即可
base_url = ''
rsp = opener.open(base_url)

cookie文件保存

from urllib import request,parse,error
from http import cookiejar
import json

#登录的入口网址,密码数据,headers
#获取cookie并且保存
url = ''
data = {}
data = parse.urlencode(data).encode()
headers = {}
# 设置保存cookie的文件,同级目录下的cookie.txt
f = r'cookie.txt'
# 声明一个MozillaCookieJar对象实例来保存cookie,之后写入文件
cookie = cookiejar.MozillaCookieJar(f)
# 利用urllib库的HTTPCookieProcessor对象来创建cookie处理器
handler = request.HTTPCookieProcessor(cookie)
# 通过handler来构建opener
opener = request.build_opener(handler)
req = request.Request(url,data=data,headers=headers)
try:
    rsp = opener.open(req)
    # 保存cookie到文件
    cookie.save(ignore_discard=True,ignore_expires=True)
    html = rsp.read().decode()
    print(html)
except error.URLError as f:
    print(e)

读取cookie文件

from urllib import request
from http.cookiejar import MozillaCookieJar

url= ''
# 加载cookie.txt
cookiejar = MozillaCookieJar("cookie.txt")
cookiejar.load(ignore_expires=True,ignore_discard=True)
handler = request.HTTPCookieProcessor(cookiejar)
opener = request.build_opener(handler)

headers = {}
req = request.Request(url,headers=headers)

resp = opener.open(req)
print(resp.read())

Requests的session保持登录状态

import requests

log_url = "http://www.renren.com/PLogin.do"
data = {"email":"自己填",'password':"自己填"}
headers = {
    'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
}
# 登录
session = requests.session()
session.post(log_url,data=data,headers=headers)

# 访问个人中心
resp = session.get('http://www.renren.com/968910325/profile')
print(resp.text)

urllib处理不信任证书

import ssl

ssl._create_default_https_context=ssl._create_unverified_context

Requests处理不信任的SSL证书:

添加verify=False

resp = requests.get('http://www.12306.cn/',verify=False)
print(resp.content.decode('utf-8'))
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值