前言
前天看到一個(gè)爬取了知乎50多萬評(píng)論的帖子, 羨慕的同時(shí)也想自己來嘗試一下狂巢〕琶看看能不能獲取一些有價(jià)值的信息。
必備知識(shí)點(diǎn)
下面簡單的來談?wù)勎覍ΤR姷姆琅老x的一些技巧的理解唧领。
headers
現(xiàn)在很多服務(wù)器都對爬蟲進(jìn)行了限制藻雌,有一個(gè)很通用的處理就是檢測“客戶端”的headers。通過這個(gè)簡單的判斷就可以判斷出客戶端是爬蟲程序還是真實(shí)的用戶斩个。(雖然這一招在Python中可以很輕松的解決)胯杭。
Referer
referer字段很實(shí)用,一方面可以用于站內(nèi)數(shù)據(jù)的防盜鏈受啥。比如我們經(jīng)常遇到的在別處復(fù)制的圖片鏈接做个,粘到我們的博客中出現(xiàn)了“被和諧”的字樣。
這就是referer起到的作用滚局,服務(wù)器在接收到一個(gè)請求的時(shí)候先判斷Referer是否為本站的地址居暖。如果是的話就返回正確的資源;如果不是核畴,就返回給客戶端預(yù)先準(zhǔn)備好的“警示”資源膝但。
所以再寫爬蟲的時(shí)候(尤其是爬人家圖片的時(shí)候),加上Referer字段會(huì)很有幫助谤草。
User-Agent
User-Agent字段更是沒的說了跟束。相信絕大部分有防爬長處理的網(wǎng)站都會(huì)判斷這個(gè)字段莺奸。來檢測客戶端是爬蟲程序還是瀏覽器。
如果是爬蟲程序(沒有添加header的程序)冀宴,服務(wù)器肯定不會(huì)返回正確的內(nèi)容啦灭贷;如果包含了這個(gè)字段,才會(huì)進(jìn)行到下一步的防爬蟲處理操作略贮。
如果網(wǎng)站僅僅做到了這一步甚疟,而你的程序又恰好添加了User-Agent,基本上就可以順利的蒙混過關(guān)了逃延。
隱藏域
很多時(shí)候览妖,我們模擬登錄的時(shí)候需要提交的數(shù)據(jù)并不僅僅是用戶名密碼,還有一些隱藏域的數(shù)據(jù)揽祥。比如拿咱們CSDN來說讽膏,查看登錄頁
https://passport.csdn.net/account/login
的時(shí)候,你會(huì)發(fā)現(xiàn)源碼中有這樣的內(nèi)容:
也就是說拄丰,如果你的程序僅僅post了username和password府树。那么是不可能進(jìn)入到webflow流程的。因?yàn)榉?wù)器端接收請求的時(shí)候還會(huì)判斷有沒有l(wèi)t和execution這兩個(gè)隱藏域的內(nèi)容料按。
其他
防止爬蟲還有很多措施奄侠,我本人經(jīng)驗(yàn)還少,所以不能在這里一一列舉了载矿。如果您有相關(guān)的經(jīng)驗(yàn)垄潮,不妨留下評(píng)論,我會(huì)及時(shí)的更新到博客中恢准,我非常的贊同大家秉承學(xué)習(xí)的理念來交流魂挂。
模擬登錄
在正式的模擬登錄知乎之前,我先來寫個(gè)簡單的小例子來加深一下印象馁筐。
模擬防爬
模擬防爬肯定是需要服務(wù)器端的支持了涂召,下面簡單的寫一下來模擬整個(gè)過程。
服務(wù)器端
login.php
先來看看: login.php
<?php
/**
* @Author: 郭 璞
* @File: login.php
* @Time: 2017/4/7
* @Contact: 1064319632@qq.com
* @blog: http://blog.csdn.net/marksinoberg
* @Description: 模擬防爬處理
**/
$username = $_POST['username'];
$password = $_POST['password'];
$token = $_POST['token'];
if (!isset($token)) {
echo "登錄失斆舫痢果正!";
exit(0);
}else{
// 這里簡單的模擬一下token的計(jì)算規(guī)則,實(shí)際中會(huì)比這更加的復(fù)雜
$target_token = $username.$username;
if ($token == $target_token){
if ($username ==='123456' and $password==='123456'){
echo "登陸成功盟迟!<br>用戶名: ".$username."<br>密碼:".$password."<br>token: ".$token;
}else{
echo "用戶名或密碼錯(cuò)誤秋泳!";
}
}else{
echo "token 驗(yàn)證失敗攒菠!";
}
}
login.html
相對應(yīng)的前端代碼簡單的寫成下面: login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>郭璞的小窩</title>
</head>
<body>
<form action="login.php" method="post">
用戶名: <input type="text" name="username" id="username" required><br>
密 碼:<input type="password" name="password" required><br>
<input type="hidden" name="token" id="token" value="">
<hr>
<input type="submit" value="登錄">
</form>
<script>
document.getElementById('username').onblur = function() {
var username = document.getElementById("username").value;
var token = document.getElementById('token');
token.value = username+username;
}
</script>
</body>
</html>
瀏覽器測試
正常提交用戶名密碼的話如下:
我們不難發(fā)現(xiàn)迫皱,服務(wù)器端和客戶端使用了相同的計(jì)算規(guī)則,這樣的話我們就可以實(shí)現(xiàn)對客戶端的登錄請求進(jìn)行一次簡答的甄選了。正常的瀏覽器請求都是沒有問題的卓起。
用戶名或者密碼填寫錯(cuò)誤的情況如下:
爬蟲沒有添加隱藏域時(shí)
用爬蟲程序運(yùn)行的話和敬,如果沒有添加隱藏域的內(nèi)容,我們就不可能正確地登錄了戏阅。那么先來看下這樣的傻瓜式爬蟲是怎么失效的吧捐名。
使用Python寫一個(gè)這樣的爬蟲用不了多少代碼狡汉,那么就用Python來寫吧。其他的接口測試工具postman骂删,selenium等等也都是很方便的秋冰,這里暫且不予考慮护昧。
# coding: utf8
# @Author: 郭 璞
# @File: sillyway.py
# @Time: 2017/4/7
# @Contact: 1064319632@qq.com
# @blog: http://blog.csdn.net/marksinoberg
# @Description: 傻瓜式爬蟲未添加隱藏域的值
import requests
url = "http://localhost/phpstorm/pachong/login.php"
payload = {
'username': '123456',
'password': '123456'
}
response = requests.post(url=url, data=payload)
print(response.text)
運(yùn)行的結(jié)果如下:
對比PHP文件對于請求的處理呈础,我們可以更加輕松的明白這個(gè)邏輯。
添加了隱藏域的爬蟲
正如上面失敗的案例笆怠,我們明白了要添加隱藏域的值的必要性铝耻。那么下面來改進(jìn)一下。
因?yàn)槲覀儭辈恢馈狈?wù)器端是怎么對token處理的具體的邏輯蹬刷。所以還是需要從客戶端的網(wǎng)頁下手。
且看下面的圖片频丘。
注意:這里僅僅是為了演示的方便办成,采用了對username字段失去焦點(diǎn)時(shí)計(jì)算token。實(shí)際上在網(wǎng)頁被拉取到客戶端瀏覽器的時(shí)候搂漠, 服務(wù)器會(huì)事先計(jì)算好token的值迂卢,并賦予到token字段的。所以大可不必計(jì)較這里的實(shí)現(xiàn)桐汤。
Python代碼
# coding: utf8
# @Author: 郭 璞
# @File: addhiddenvalue.py
# @Time: 2017/4/7
# @Contact: 1064319632@qq.com
# @blog: http://blog.csdn.net/marksinoberg
# @Description: 添加了隱藏域信息的爬蟲
import requests
## 先獲取一下token的內(nèi)容值而克,方便接下來的處理
url = 'http://localhost/phpstorm/pachong/login.php'
payload = {
'username': '123456',
'password': '123456',
'token': '123456123456'
}
response = requests.post(url, data=payload)
print(response.text)
實(shí)現(xiàn)效果如下:
現(xiàn)在是否對于隱藏域有了更深的認(rèn)識(shí)了呢?
知乎模擬登錄
按照我們剛才的邏輯怔毛,我們要做的就是:
先打開預(yù)登陸界面员萍,目標(biāo):得到必須提交的隱藏域的值
然后通過post再次訪問該路徑(準(zhǔn)備好了一切必須的信息)
獲取網(wǎng)頁內(nèi)容并進(jìn)行解析,或者做其他的處理拣度。
思路很清晰了碎绎,下面就可以直接上代碼了。
# coding: utf8
# @Author: 郭 璞
# @File: ZhiHuLogin.py
# @Time: 2017/4/7
# @Contact: 1064319632@qq.com
# @blog: http://blog.csdn.net/marksinoberg
# @Description: 模擬登陸知乎
import re
from bs4 import BeautifulSoup
import subprocess, os
import json
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Host": "www.zhihu.com",
"Upgrade-Insecure-Requests": "1",
}
############################# 從郵箱方式登錄
loginurl = 'http://www.zhihu.com/login/email'
session = requests.session()
html = session.get(url=loginurl, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
print(soup)
xsrf_token = soup.find('input', {'name':'_xsrf'})['value']
print("登錄xsrf_token: "+xsrf_token)
############################ 下載驗(yàn)證碼備用
checkcodeurl = 'http://www.zhihu.com/captcha.gif'
checkcode = session.get(url=checkcodeurl, headers=headers).content
with open('./checkcode.png', 'wb') as f:
f.write(checkcode)
print('已經(jīng)打開驗(yàn)證碼抗果,請輸入')
# subprocess.call('./checkcode.png', shell=True)
os.startfile(r'checkcode.png')
checkcode = input('請輸入驗(yàn)證碼:')
os.remove(r'checkcode.png')
############################ 開始登陸
payload = {
'_xsrf': xsrf_token,
'email': input('請輸入用戶名:'),
'password': getpass.getpass(prompt="請輸入密碼:"),#input('請輸入密碼:'),
'remeber_me': 'true',
'captcha': checkcode
}
response = session.post(loginurl, data=payload)
print("*"*100)
result = response.text
print("登錄消息為:"+result)
tempurl = 'https://www.zhihu.com/question/57964452/answer/155231804'
tempresponse = session.get(tempurl, headers=headers)
soup = BeautifulSoup(tempresponse.text, 'html.parser')
print(soup.title)
實(shí)現(xiàn)的效果如下
觀察動(dòng)態(tài)圖筋帖,不難發(fā)現(xiàn)對于https://www.zhihu.com/question/57964452/answer/155231804
界面,我們正確的獲取到了title的內(nèi)容冤馏。(也許你會(huì)說日麸,正常訪問也會(huì)獲取到這個(gè)內(nèi)容的,但是我們是從已登錄的session上獲取的逮光,請記住這一點(diǎn)哈代箭。)墩划。
更新版知乎模擬登陸
代碼部分
# coding: utf8
# @Author: 郭 璞
# @File: MyZhiHuLogin.py
# @Time: 2017/4/8
# @Contact: 1064319632@qq.com
# @blog: http://blog.csdn.net/marksinoberg
# @Description: 我的模擬登錄知乎
import requests
from bs4 import BeautifulSoup
import os, time
import re
# import http.cookiejar as cookielib
# 構(gòu)造 Request headers
agent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36'
headers = {
"Host": "www.zhihu.com",
"Referer": "https://www.zhihu.com/",
'User-Agent': agent
}
######### 構(gòu)造用于網(wǎng)絡(luò)請求的session
session = requests.Session()
# session.cookies = cookielib.LWPCookieJar(filename='zhihucookie')
# try:
# session.cookies.load(ignore_discard=True)
# except:
# print('cookie 文件未能加載')
############ 獲取xsrf_token
homeurl = 'https://www.zhihu.com'
homeresponse = session.get(url=homeurl, headers=headers)
homesoup = BeautifulSoup(homeresponse.text, 'html.parser')
xsrfinput = homesoup.find('input', {'name': '_xsrf'})
xsrf_token = xsrfinput['value']
print("獲取到的xsrf_token為: ", xsrf_token)
########## 獲取驗(yàn)證碼文件
randomtime = str(int(time.time() * 1000))
captchaurl = 'https://www.zhihu.com/captcha.gif?r='+\
randomtime+"&type=login"
captcharesponse = session.get(url=captchaurl, headers=headers)
with open('checkcode.gif', 'wb') as f:
f.write(captcharesponse.content)
f.close()
# os.startfile('checkcode.gif')
captcha = input('請輸入驗(yàn)證碼:')
print(captcha)
########### 開始登陸
headers['X-Xsrftoken'] = xsrf_token
headers['X-Requested-With'] = 'XMLHttpRequest'
loginurl = 'https://www.zhihu.com/login/email'
postdata = {
'_xsrf': xsrf_token,
'email': '郵箱@qq.com',
'password': '密碼'
}
loginresponse = session.post(url=loginurl, headers=headers, data=postdata)
print('服務(wù)器端返回響應(yīng)碼:', loginresponse.status_code)
print(loginresponse.json())
# 驗(yàn)證碼問題輸入導(dǎo)致失敗: 猜測這個(gè)問題是由于session中對于驗(yàn)證碼的請求過期導(dǎo)致
if loginresponse.json()['r']==1:
# 重新輸入驗(yàn)證碼,再次運(yùn)行代碼則正常梢卸。也就是說可以再第一次不輸入驗(yàn)證碼走诞,或者輸入一個(gè)錯(cuò)誤的驗(yàn)證碼,只有第二次才是有效的
randomtime = str(int(time.time() * 1000))
captchaurl = 'https://www.zhihu.com/captcha.gif?r=' + \
randomtime + "&type=login"
captcharesponse = session.get(url=captchaurl, headers=headers)
with open('checkcode.gif', 'wb') as f:
f.write(captcharesponse.content)
f.close()
os.startfile('checkcode.gif')
captcha = input('請輸入驗(yàn)證碼:')
print(captcha)
postdata['captcha'] = captcha
loginresponse = session.post(url=loginurl, headers=headers, data=postdata)
print('服務(wù)器端返回響應(yīng)碼:', loginresponse.status_code)
print(loginresponse.json())
##########################保存登陸后的cookie信息
# session.cookies.save()
############################判斷是否登錄成功
profileurl = 'https://www.zhihu.com/settings/profile'
profileresponse = session.get(url=profileurl, headers=headers)
print('profile頁面響應(yīng)碼:', profileresponse.status_code)
profilesoup = BeautifulSoup(profileresponse.text, 'html.parser')
div = profilesoup.find('div', {'id': 'rename-section'})
print(div)
驗(yàn)證效果
總結(jié)
經(jīng)過了今天的測試蛤高,發(fā)現(xiàn)自己之前對于網(wǎng)頁的處理理解的還是不夠到位蚣旱。
對于“靜態(tài)頁面”,常用的urllib, requests應(yīng)該是可以滿足需要的了戴陡。
對于動(dòng)態(tài)頁面的爬取塞绿,可以使用無頭瀏覽器PhantomJS,Selenium等來實(shí)現(xiàn)恤批。
但是一直處理的不夠精簡异吻,導(dǎo)致在爬一些重定向頁面的過程中出現(xiàn)了很多意想不到的問題。
在這塊的爬蟲程序還有很多地方需要進(jìn)行完善啊喜庞。
另外模擬登錄還有一個(gè)利器诀浪,那就是cookie。下次有時(shí)間的話再來學(xué)習(xí)一下使用cookie來實(shí)現(xiàn)延都。今天就先到這里吧雷猪。
參考鏈接:
http://blog.csdn.net/shell_zero/article/details/50783078