爬蟲之 cookie , 驗證碼,模擬登錄,線程

需求文檔的定製
糗事百科的段子內容和做者(xpath的管道符)名稱進行爬取,而後存儲到mysql中or文本
http://sc.chinaz.com/jianli/free.html爬取簡歷模板

HTTPConnectionPool(host:XX)Max retries exceeded with url。
緣由:
1.當你在短期內發起高頻請求的時候,http的鏈接池中的鏈接資源被耗盡。
Connection:keep-alive
2.ip被封
解決:
Connection:'close'
爬取一個你感興趣的網站數據

 

 
數據解析
目的:實現聚焦爬蟲!!!
數據解析的通用原理:
1.標籤訂位
2.數據提取
bs4:
1.實例化一個BeautifulSoup的對象,將即將被解析的頁面源碼加載到該對象
2.屬性和方法實現標籤訂位和數據的提取
soup.tagName
soup.find/find_all('tagName',class_='value')
select('選擇器'):返回的是列表
tag.text/string:字符串
tag['attrName']
xpath:xpath方法返回的必定是列表
表達式最左側的/ 和 //的區別
非最左側的/和//的區別
屬性定位://div[@class="xxx"]
索引定位://div[2]
/text() //text()
/div/a/@href

 

 
  • 代理操做
  • cookie的操做
  • 驗證碼的識別
  • 模擬登錄
 
代理操做
目的:爲解決ip被封的狀況
什麼是代理?
代理服務器:fiddler
爲何使用了代理就能夠更改請求對應的ip呢?
本機的請求會先發送給代理服務器,代理服務器會接受本機發送過來的請求(當前請求對應的ip就是本機ip),而後代理服務器會將該請求進行轉發,轉發以後的請求對應的ip就是代理服務器的ip。
提供免費代理ip的平臺
www.goubanjia.com
快代理
西祠代理
代理精靈:http://http.zhiliandaili.cn
代理ip的匿名度

透明:使用了透明的代理ip,則對方服務器知道你當前發起的請求使用了代理服務器而且能夠監測到你真實的ip
匿名:知道你使用了代理服務器不知道你的真實ip
高匿:不知道你使用了代理服務器也不知道你的真實ip
代理ip的類型

http:該類型的代理IP只能夠轉發http協議的請求
https:只能夠轉發https協議的請求

 

 
 
 
#代理測試
import requests
from lxml import etree
import random
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
​
 
 
#構建一個簡易的ip池
proxy_list = [
    {'https':'212.64.51.13:8888'},
    {'https':'212.64.51.13:8888'},
    {'https':'212.64.51.13:8888'},
]
 

 
 
 
url = 'https://www.baidu.com/s?ie=UTF-8&wd=ip'
#proxies指定代理ip
page_text = requests.get(url=url,headers=headers,proxies=random.choice(proxy_list)).text
with open('ip.html','w',encoding='utf-8') as fp:
    fp.write(page_text)
 

 

 
 
如何構建一個標準的代理ip池    (goubanjia    代理精靈    )
1.取各大平臺中爬取大量的免費代理ip
2.校驗出可用的代理ip
使用每個代理ip進行請求發送,監測響應狀態碼是否爲200
3.將可用的代理ip進行存儲(redis)
 
all_ips = []
ip_url = 'http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&groupid=0&qty=53&time=1&pro=&city=&port=1&format=html&ss=5&css=&dt=1&specialTxt=3&specialJson='
page_text = requests.get(ip_url,headers=headers).text
tree = etree.HTML(page_text)
ip_list = tree.xpath('//body//text()')
for ip in ip_list:
    ip = {'https':ip}
    all_ips.append(ip)
 
 
In [29]:
 
 
 
 
 
url = 'https://www.xicidaili.com/nn/%d'
for page in range(1,100):
    print('正在爬取第{}頁的數據!'.format(page))
    new_url = format(url%page)
    page_text = requests.get(url=new_url,headers=headers,proxies=random.choice(all_ips)).text
    tree = etree.HTML(page_text)
    tr_list = tree.xpath('//*[@id="ip_list"]//tr')[1:]
    for tr in tr_list:
        ip = tr.xpath('./td[2]/text()')[0]
        port = tr.xpath('./td[3]/text()')[0]
        ip_type = tr.xpath('./td[6]/text()')[0]
        dic = {
            'ip':ip,
            'port':port,
            'type':ip_type
        }
        all_ips.append(dic)
print(len(all_ips))        
 

 

 
 
  • Cookie
    • 什麼是cookie?
      • 保存在客戶端的鍵值對
  • 爬取雪球網中的新聞數據:https://xueqiu.com/
 
 
 
 
 
#經過抓包工具捕獲的基於ajax請求的數據包中提取的url
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20343389&count=15&category=-1'
json_data = requests.get(url=url,headers=headers).json()
print(json_data)
​
 
 
 
{'error_description': '遇到錯誤,請刷新頁面或者從新登陸賬號後再試', 'error_uri': '/v4/statuses/public_timeline_by_category.json', 'error_data': None, 'error_code': '400016'}
 
cookie的破解方式
手動處理:
經過抓包工具將請求攜帶的cookie添加到headers中
弊端:cookie會有有效時長,cookie仍是動態變化
自動處理:
使用session進行cookie的自動保存和攜帶
session是能夠進行請求發送的,發送請求的方式和requests同樣
若是使用session進行請求發送,在請求的過程當中產生了cookie,則該cookie會被自動存儲到session對象中
若是使用了攜帶cookie的session再次進行請求發送,則該次請求就時攜帶cookie進行的請求發送

 
 
 
#建立一個session對象
session = requests.Session()
#將cookie保存到session對象中
first_url = 'https://xueqiu.com/'
session.get(url=first_url,headers=headers)#爲了獲取cookie且將cookie存儲到session中
​
url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=20343389&count=15&category=-1'
json_data = session.get(url=url,headers=headers).json()#攜帶cookie發起的請求
json_data
 

 

. . .
 
 
 
 
 
 
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=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=params, headers=self.headers)
        return r.json()
 



def getCodeImgText(imgPath,imgType):
 
          
    chaojiying = Chaojiying_Client('bobo328410948', 'bobo328410948', '899370')#用戶中心>>軟件ID 生成一個替換 96001
 
          
    im = open(imgPath, 'rb').read()#本地圖片文件路徑 來替換 a.jpg 有時WIN系統需要//
 
          
    return chaojiying.PostPic(im,imgType)['pic_str']
 

 

 
 
 
 
 
#古詩文網的驗證碼識別操做
url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
page_text = requests.get(url,headers=headers).text
tree = etree.HTML(page_text)
img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
print(img_src)
img_data = requests.get(url=img_src,headers=headers).content
with open('codeImg.jpg','wb') as fp:
    fp.write(img_data)
#進行驗證碼的識別
getCodeImgText('codeImg.jpg',1004)
 
 
 
https://so.gushiwen.org/RandCode.ashx

'abt9'

 

 
 
 
 
 
s = requests.Session()
#模擬登錄
#古詩文網的驗證碼識別操做
url = 'https://so.gushiwen.org/user/login.aspx?from=http://so.gushiwen.org/user/collect.aspx'
page_text = s.get(url,headers=headers).text
tree = etree.HTML(page_text)
img_src = 'https://so.gushiwen.org'+tree.xpath('//*[@id="imgCode"]/@src')[0]
img_data = s.get(url=img_src,headers=headers).content
with open('codeImg.jpg','wb') as fp:
    fp.write(img_data)
#解析動態變化的請求參數
__VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
__VIEWSTATEGENERATOR = tree.xpath('//input[@id="__VIEWSTATEGENERATOR"]/@value')[0]
print(__VIEWSTATE,__VIEWSTATEGENERATOR)
#進行驗證碼的識別
code_text = getCodeImgText('codeImg.jpg',1004)
print(code_text)
login_url = 'https://so.gushiwen.org/user/login.aspx?from=http%3a%2f%2fso.gushiwen.org%2fuser%2fcollect.aspx'
data = {
    #下面兩個請求參數是動態變化
    #通長狀況下動態變化的請求參數會被隱藏在前臺頁面中
    '__VIEWSTATE': __VIEWSTATE,
    '__VIEWSTATEGENERATOR': __VIEWSTATEGENERATOR,
    'from': 'http://so.gushiwen.org/user/collect.aspx',
    'email': 'www.zhangbowudi@qq.com',
    'pwd': 'bobo328410948',
    'code': code_text,
    'denglu': '登陸',
}
#登錄成功以後對應的首頁頁面源碼
main_page_text = s.post(url=login_url,headers=headers,data=data).text
with open('./main.html','w',encoding='utf-8') as fp:
    fp.write(main_page_text)
 
 
 
bYMP3RE7FaZbXTvLHv5jqvU+oBFf724TXFoNPnly3qgtvK1IuW803mee/rn7QSnnThGZKU/Xx0PsTcksCzRzv6kE1l1FN3W+2lev+CzshULLoDTndVVDOQcl4mk= C93BE1AE
5zz8
 
反爬機制
cookie
動態變化的請求參數
驗證碼

 

 

 

In [2]:
 
 
 
 
 
import requests
import time
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
 
 
 

同步代碼

 
  • flask服務器代碼:
In [ ]:
 
 
 
 
 
from flask import Flask
from time import sleep
app = Flask(__name__)
@app.route('/bobo')
def index1():
    sleep(2)
    return 'hello bobo!'
@app.route('/jay')
def index2():
    sleep(2)
    return 'hello jay!'
@app.route('/tom')
def index3():
    sleep(2)
    return 'hello tom!'
app.run()
 
 
In [ ]:
 
 
 
 
 
 
 
In [3]:
 
 
 
 
 
start = time.time()
urls = [
    'http://127.0.0.1:5000/bobo',
    'http://127.0.0.1:5000/jay',
    'http://127.0.0.1:5000/tom',
]
for url in urls:
    page_text = requests.get(url,headers=headers).text
    print(page_text)
 
                          
print(time.time()-start)
 
                         
 
 
 
hello bobo!
hello jay!
hello tom!
6.016878366470337
 

基於線程池實現異步爬取

from multiprocessing.dummy import Pool #線程池模塊
#必須只能夠有一個參數
def my_requests(url):
    return requests.get(url=url,headers=headers).text
start = time.time()
urls = [
    'http://127.0.0.1:5000/bobo',
    'http://127.0.0.1:5000/jay',
    'http://127.0.0.1:5000/tom',
]
pool = Pool(3)
#map:兩個參數
#參數1:自定義的函數,必須只能夠有一個參數
#參數2:列表or字典
#map的做用就是讓參數1表示的自定義的函數異步處理參數2對應的列表或者字典中的元素
page_texes = pool.map(my_requests,urls)
print(page_texes)
print(time.time()-start)
['hello bobo!', 'hello jay!', 'hello tom!']
2.0126171112060547
 
  • asyncio
    • 如何產生一個攜程對象
    • 什麼是任務對象
    • 任務對象和攜程對象的區別
    • 任務對象如何綁定一個回調呢
    • 什麼是事件循環呢?
  • aiohttp
相關文章
相關標籤/搜索