代理(反爬機制)
短時間向一個服務器發起高頻請求,會被認定為例外請求,將當前IP列入黑名單
- 概念:在爬蟲中指的就是代理服務器
- 代理服務器的作用:
- 攔截請求和回應,進行轉發
- 代理和爬蟲之間的關聯?
- 如果pc端IP被禁掉后,我們就可以使用代理機制更換請求的IP
- 如何獲取相關的代理服務器
- 快代理:https://www.kuaidaili.com/
- 西刺代理:https://www.xicidaili.com/
- 代理精靈:http://http.zhiliandaili.com/(推薦使用,便宜)
- 購半價:http://www.goubanjia.com/
- 匿名度
- 透明:知道你使用代理,也知道你的真實IP
- 匿名:對方服務器知道你使用了代理機制,但是不會到你的真實IP
- 高匿名:對方服務器不知道你使用了代理機制,更不知道你的真實IP
- 型別
http:只可以攔截轉發http協議的請求https:證書秘鑰加密,只可以轉發攔截https的請求
代理的基本使用
- 語法結構
get/post(proxies={'http/https':'ip:prot'})
案例:基于搜狗ip搜索
- 搜索到的頁面中會顯示該請求對應的ip地址
- https://www.sogou.com/web?query=ip
import requests
from lxml import etree
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
url = "https://www.sogou.com/web?query=ip"
# 代理機制對應的就是get或者post方法中一個叫做proxies的引數
page_text = requests.get(url=url,headers=headers,proxies={"https":'221.1.200.242:38652'}).text
tree = etree.HTML(page_text)
# 在Xpath運算式中不能出現tbody標簽
ip = tree.xpath('//*[@id="ipsearchresult"]/strong/text()')[0]
print(ip)
代理池
爬取某一網站請求過多會被封IP,所以要使用代理池
案例:將西刺代理中的免費代理IP進行爬取
- https://www.xicidaili.com/nn/
import requests
import random
from lxml import etree
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
all_ips = []
api_url = "購買代理精靈付費ip生成的html的地址"
api_text = requests.get(url=api_url,headers=headers).text
api_tree = etree.HTML(api_text)
datas = api_tree.path('//body//text()') # 取出所有文本
for data in datas:
dic = {
'https':data
}
all_ips.append(dic) # 以字典的形式[{},{}...]
url = "https://www.xicidaili.com/nn/%d" # 定義一個通用的url模板
ip_datas = [] # 決議到的所有資料
for page_num in range(1,50): # 頁碼越多,代理池ip就越多,ip有效時長多一點
new_url = format(url%page_num)
page_text=requests.get(url=new_url,headers=headers,proxies=random.choice(all_ips)).text
tree =etree.HTML(page_text)
tr_lst = tree.xpath('//*[@id="ip_list"]//tr')[1:]
for tr in tr_lst:# 區域資料決議
ip = tr.xpath('./td[2]/text()')[0]
prot = tr.xpath('./td[3]/text()')[0]
dic_ = {
"https":ip + ":" + prot
}
ip_datas.append(dic_)
print(len(datas)) # 爬取到的ip
模擬登錄
- 為什么要實作模擬登錄?
- 相關頁面是必須經過登陸之后才可見的
驗證碼處理
- 使用相關的打碼平臺進行驗證碼的動態識別
打碼平臺
- 超級鷹(推薦,可以識別12306驗證)
- http://www.chaojiying.com/
- 云打碼
- http://yundama.com/
- 創建開發者帳號,普通用戶登錄無法創建應用id
超級鷹使用流程
-
注冊【用戶中心】身份的帳號
-
登錄
-
創建一個軟體
用戶中心→軟體ID→添加軟體
-
下載示例代碼
-
#!/usr/bin/env python
# coding:utf-8
import requests
from hashlib import md5
class Chaojiying_Client(object):
def __init__(self, username, password, soft_id):
self.username = username
password = password.encode('utf8')
self.password = md5(password).hexdigest()
self.soft_id = soft_id
self.base_params = {
'user': self.username,
'pass2': self.password,
'softid': self.soft_id,
}
self.headers = {
'Connection': 'Keep-Alive',
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
}
def PostPic(self, im, codetype):
"""
im: 圖片位元組
codetype: 題目型別 參考 http://www.chaojiying.com/price.html
"""
params = {
'codetype': codetype,
}
params.update(self.base_params)
files = {'userfile': ('ccc.jpg', im)}
r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=https://www.cnblogs.com/Golanguage/p/params, files=files, headers=self.headers)
return r.json()
def ReportError(self, im_id):"""
im_id:報錯題目的圖片ID
"""
params = {
'id': im_id,
}
params.update(self.base_params)
r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=https://www.cnblogs.com/Golanguage/p/params, headers=self.headers)
return r.json()"""
if __name__ == '__main__':
chaojiying = Chaojiying_Client('超級鷹用戶名', '超級鷹用戶名的密碼', '96001') #用戶中心>>軟體ID 生成一個替換 96001
im = open('a.jpg', 'rb').read() #本地圖片檔案路徑 來替換 a.jpg 有時WIN系統須要//
print chaojiying.PostPic(im, 1902) #1902 驗證碼型別 官方網站>>價格體系 3.4+版 print 后要加()
"""
# 封裝一個驗證碼識別的函式
def transform_code(imgPath,imgType):
chaojiying = Chaojiying_Client('超級鷹用戶名', '超級鷹密碼', '軟體ID')
im = open(imgPath, 'rb').read()
return chaojiying.PostPic(im, imgType)['pic_str']
cookie處理
手動處理
- 將請求攜帶的
cookie封裝到headers中
自動處理
- session物件,該物件和requests都可以進行get和post請求的發送; 使用session物件發送請求程序中,產生的cookie會被自動存盤到session物件中; cookie存盤到session物件中后,再次使用session進行請求發送,則該次請求就是攜帶著cookie發送的請求,
- session處理cookie的時候,session物件最少發幾次請求?
- 兩次,第一次是為了獲取和存盤cookie;第二次才是攜帶cookie進行的請求發送,
- session = requests.Session()
案例:爬取雪球網中的新聞標題和內容
手動處理
- 有局限性,不能保證cookie的有效時長
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
# 手動處理
'Cookie':'aliyungf_tc=AQAAANpdTCedNgQA0EVI33fxpCso1BVS; acw_tc=2760823015846080972884781e8f986f089c7939870e775a86ffb898ca91d4; xq_a_token=a664afb60c7036c7947578ac1a5860c4cfb6b3b5; xqat=a664afb60c7036c7947578ac1a5860c4cfb6b3b5; xq_r_token=01d9e7361ed17caf0fa5eff6465d1c90dbde9ae2; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOi0xLCJpc3MiOiJ1YyIsImV4cCI6MTU4NTM2MjYwNywiY3RtIjoxNTg0NjA4MDcwNzY4LCJjaWQiOiJkOWQwbjRBWnVwIn0.gwlwGxWjdyWuNGniaTqxswJjO6nKJY9PCJ0aCif9vuHvsUXEI7iW7_wIvBhDC1WTk86J8ayJ_bZd-KxySHAd1Z8kyM6TV80l931tmestgj1I6uP66WsaUZ3PYDBC4KO1chuEqmw_nCa1UhSjWrc-4moKmMbbll6RyvPSocfRxrvrQY-DX_1uBcs_BsRcAakyOEcWxO01tgfQQoVEbd9apgudAXTQc3haJPTLZpqYH62CYYIJZwHGsbI0emF1k1Wmp_539girZEmPnE7NgK6N1I8tqTdh_XaDTFfFK07G177w84nVuJfsB8hPca6rzYDUGPAMAWqQJcPEUSDzDKhkdA; u=301584608097293; Hm_lvt_1db88642e346389874251b5a1eded6e3=1584608100; device_id=24700f9f1986800ab4fcc880530dd0ed; cookiesu=901584608234987; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1584608235'
}
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?'
params = {
'since_id': '-1',
'max_id': '20369159',
'count': '15',
'category': '-1',
}
page_json = requests.get(url=url,headers=headers,params=params).json()
print(page_json)
自動處理
- 推薦使用,每次都可以獲取新的cookie
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
# 實體化一個session物件
session = requests.Session()
# 試圖將cookie獲取且存盤到session物件中,url得試著來
session.get('https://xueqiu.com/',headers=headers)
# url地址
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?'
# 發請求索攜帶的引數
params = {
'since_id': '-1',
'max_id': '20369159',
'count': '15',
'category': '-1',
}
# 攜帶cookie的發送求情
page_json = session.get(url=url,headers=headers,params=params).json()
print(page_json)
案例:古詩文網模擬登陸
- url:https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx
- 分析
- 通過抓包工具定位到點擊登錄按鈕對應的資料包(包含用戶名、密碼、驗證碼)
- 從資料包中取出請求的url,請求方式,請求引數
import requests
from lxml import etree
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
# 網站涉及到cookie,直接實體化session物件,所有請求都用session發送
session = requests.Session()
# 驗證碼識別
first_url = "https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx"
page_text = session.get(first_url,headers=headers).text
tree = etree.HTML(page_text)
code_img_src = "https://so.gushiwen.org/" + tree.xpath('//*[@id="imgCode"]/@src')[0]
# 對驗證碼圖片的地址進行發請求,產生了cookie
code_img_data = https://www.cnblogs.com/Golanguage/p/session.get(code_img_src,headers=headers).content
with open('./code.jpg','wb') as f:
f.write(code_img_data)
# 基于超級鷹識別驗證碼,可以將超級鷹的包匯入,因為我用的是jupyter,上面運行過超級鷹的包和我寫的函式,所以直接拿來用了,使用pycharm的話就匯入一下
# from chaojiying import transform_code
code_img_text = transform_code('./code.jpg',1902)
# 識別驗證碼也不是百分百成功的,所以查看一下
print(code_img_text)
url = 'https://so.gushiwen.org/user/login.aspx'
# 動態引數
data = https://www.cnblogs.com/Golanguage/p/{'__VIEWSTATE': 'ldci9GbqVEF2rdreR42gQu3m7xrlS5IibH9mPop+Qc1ONCWpo9EQCzSxUHhInXI26x0x19nb1l6gw26SC8qi4q/XnaPcK67OGf/fGDOfhuewFPnrLznJctqf/no=',
'__VIEWSTATEGENERATOR': 'C93BE1AE',
'from': 'http://so.gushiwen.org/user/collect.aspx',
'email': '[email protected]',
'pwd': '177183sy',
'code': code_img_text,
'denglu': '登錄',
}
page_text = session.post(url=url,headers=headers,data=https://www.cnblogs.com/Golanguage/p/data).text
with open('./古詩文.html','w',encoding='utf-8') as f:
# 將登陸后的頁面持久化存盤
f.write(page_text)
遇到了動態變化的請求引數該如何處理?
- 通常情況下,動態變化的請求引數的值都會被隱藏在前臺頁面中
- 基于抓包工具進行全域搜索(基于js逆向獲取相關的引數值)
語音合成
基于百度AI開放平臺
- 在線合成
Python-SDK檔案地址:https://cloud.baidu.com/doc/SPEECH/s/zk4nlz99s
案例:文本資料合成音頻檔案
- 需求:爬取文本資料將其通過百度ai的語音合成功能將文字合成音頻檔案,并將音頻檔案部署到Flask服務器中進行播放
- 爬取段子網的一句話段子為例,合成音頻檔案
import requests
import os
from lxml import etree
from aip import AipSpeech
# 請求頭資訊
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'
}
# 實體化一個AipSpeech物件
""" 你的 APPID AK SK """
APP_ID = '18937972'
API_KEY = 'zDkCBvIFz6trOvE2TXdELcgS'
SECRET_KEY = 'oWRRLM2iEBWA2vF8HU4um8Q5oEzwUAnp'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# 創建存放音頻的檔案夾
dirname = 'static'
if not os.path.exists(dirname):
os.mkdir(dirname)
# 通用url地址
ALL_URL = 'https://duanziwang.com/category/%E4%B8%80%E5%8F%A5%E8%AF%9D%E6%AE%B5%E5%AD%90/{}/'
# 全站爬取,隨便爬取10頁
for num in range(1,11):
url = ALL_URL.format(num)
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
article_list = tree.xpath('/html/body/section/div/div/main/article')
for art in article_list:
# 采集音頻檔案的存盤路徑、名字、后綴
title = "./static/" + art.xpath('./div[1]/h1/a/text()')[0] + ".mp3"
content = art.xpath('./div[2]/p/text()')[0]
# 百度ai介面呼叫
result = client.synthesis(content, 'zh', 1, {
# 音量1-15
'vol': 5,
# 發聲,0女,1男
'per': 0,
# 語速1-9
'spd': 5,
})
# 識別正確回傳語音二進制 錯誤則回傳dict 參照下面錯誤碼
if not isinstance(result, dict):
with open(title, 'wb') as f:
f.write(result)
print("over!")
Flask搭建
- 安裝
pip install Flask
server.py
from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/index')
def index():
mp3_list = []
file_list = os.listdir('./static')
for i in file_list:
i = "/static/" + i
mp3_list.append(i)
return render_template('test.html', mp3_list=mp3_list)
if __name__ == '__main__':
app.run(debug=True)
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for i in mp3_list %}
<div>
<audio src="https://www.cnblogs.com/Golanguage/p/{{ i }}" controls="controls"></audio>
</div>
{% endfor %}
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/170368.html
標籤:Python
上一篇:騰訊IM
