作為一個(gè)Python小白,在經(jīng)過一個(gè)大牛的安利下,迅速將魔爪伸向了Python。作為一個(gè)小白,今天分享下已經(jīng)被大牛們玩壞的知乎爬蟲,各位看官你看好了。
1. 我為什么要爬取回答
其實(shí)我只是好奇,加上為了快速掌握基本的語法,就研究了一下。
2. 如何實(shí)現(xiàn)
懶得說了,你自己看代碼吧:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Filename : ZhiHuSpider.py
import time
import re
import requests
import http.cookiejar
from PIL import Image
import json
from bs4 import BeautifulSoup
class ZhiHuSpider(object):
def __init__(self):
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36',
"Host": "www.zhihu.com",
"Referer": "https://www.zhihu.com/",
}
# 建立一個(gè)會話,可以把同一用戶的不同請求聯(lián)系起來;直到會話結(jié)束都會自動處理cookies
self.session = requests.Session()
self.session.keep_alive = False
# 建立LWPCookieJar實(shí)例,可以存Set-Cookie3類型的文件。
# 而MozillaCookieJar類是存為'/.txt'格式的文件
self.session.cookies = http.cookiejar.LWPCookieJar("cookie")
# 若本地有cookie則不用再post數(shù)據(jù)了
try:
self.session.cookies.load(ignore_discard=True)
print('Cookie加載成功!')
except IOError:
print('Cookie未加載!')
def get_xsrf(self):
"""
獲取參數(shù)_xsrf
"""
response = self.session.get('https://www.zhihu.com', headers=self.headers)
html = response.text
get_xsrf_pattern = re.compile(r'<input type="hidden" name="_xsrf" value="(.*?)"')
_xsrf = re.findall(get_xsrf_pattern, html)[0]
return _xsrf
def get_captcha(self):
"""
獲取驗(yàn)證碼本地顯示
返回你輸入的驗(yàn)證碼
"""
t = str(int(time.time() * 1000))
captcha_url = 'http://www.zhihu.com/captcha.gif?r=' + t + "&type=login"
response = self.session.get(captcha_url, headers=self.headers)
with open('cptcha.gif', 'wb') as f:
f.write(response.content)
# Pillow顯示驗(yàn)證碼
im = Image.open('cptcha.gif')
im.show()
captcha = input('本次登錄需要輸入驗(yàn)證碼: ')
return captcha
def login(self, username, password):
"""
輸入自己的賬號密碼,模擬登錄知乎
"""
# 檢測到11位數(shù)字則是手機(jī)登錄
if re.match(r'\d{11}$', username):
url = 'http://www.zhihu.com/login/phone_num'
data = {'_xsrf': self.get_xsrf(),
'password': password,
'remember_me': 'true',
'phone_num': username
}
else:
url = 'https://www.zhihu.com/login/email'
data = {'_xsrf': self.get_xsrf(),
'password': password,
'remember_me': 'true',
'email': username
}
# 若不用驗(yàn)證碼,直接登錄
result = self.session.post(url, data=data, headers=self.headers)
# 打印返回的響應(yīng),r = 1代表響應(yīng)失敗,msg里是失敗的原因
# loads可以反序列化內(nèi)置數(shù)據(jù)類型,而load可以從文件讀取
if (json.loads(result.text))["r"] == 1:
# 要用驗(yàn)證碼,post后登錄
data['captcha'] = self.get_captcha()
result = self.session.post(url, data=data, headers=self.headers)
print((json.loads(result.text))['msg'])
# 保存cookie到本地
self.session.cookies.save(ignore_discard=True, ignore_expires=True)
def isLogin(self):
# 通過查看用戶個(gè)人信息來判斷是否已經(jīng)登錄
url = "https://www.zhihu.com/settings/profile"
# 禁止重定向,否則登錄失敗重定向到首頁也是響應(yīng)200
login_code = self.session.get(url, headers=self.headers, allow_redirects=False,verify=False).status_code
if login_code == 200:
return True
else:
return False
def getUserInfo(self, userId):
url = 'https://www.zhihu.com/people/' + userId + '/activities'
response = self.session.get(url, headers=self.headers)
soup = BeautifulSoup(response.content, 'lxml')
name = soup.find_all('span', {'class': 'ProfileHeader-name'})[0].string
print(name)
def getQsAnswer(self, questionId):
# 每次我們?nèi)?0條回答
limit = 10
# 獲取答案時(shí)的偏移量
offset = 0
# 開始時(shí)假設(shè)當(dāng)前有這么多的回答,得到請求后我再解析
total = 2 * limit;
# 我們當(dāng)前已記錄的回答數(shù)量
record_num = 0
# 定義問題的標(biāo)題,為了避免獲取失敗,我們在此先賦值
title = questionId
# 存儲所有的答案信息
answer_info = []
print('Fetch info start...')
while record_num < total:
# 開始獲取數(shù)據(jù)
# 我們獲取數(shù)據(jù)的URL格式是什么樣呢?
# https://www.zhihu.com/api/v4/questions/39162814/answers?
# sort_by=default&include=data[*].is_normal,content&limit=5&offset=0
url = 'https://www.zhihu.com/api/v4/questions/' \
+ questionId + '/answers' \
'?sort_by=default&include=data[*].is_normal,voteup_count,content' \
'&limit=' + str(limit) + '&offset=' + str(offset)
response = self.session.get(url, headers=self.headers)
# 返回的信息為json類型
response = json.loads(response.content)
# 其中的paging實(shí)體包含了前一頁&下一頁的URL,可據(jù)此進(jìn)行循環(huán)遍歷獲取回答的內(nèi)容
# 我們先來看下總共有多少回答
total = response['paging']['totals']
# 本次請求返回的實(shí)體信息數(shù)組
datas = response['data']
# 遍歷信息并記錄
if datas is not None:
if total <= 0:
break
for data in datas:
dr = re.compile(r'<[^>]+>', re.S)
content = dr.sub('', data['content'])
answer = data['author']['name'] + ' ' + str(data['voteup_count']) + ' 人點(diǎn)贊' + '\n'
answer = answer + 'Answer:' + content + '\n'
answer_info.append('\n')
answer_info.append(answer)
answer_info.append('\n')
answer_info.append('------------------------------')
answer_info.append('\n')
# 獲取問題的title
title = data['question']['title']
# 請求的向后偏移量
offset += len(datas)
record_num += len(datas)
# 如果獲取的數(shù)組size小于limit,循環(huán)結(jié)束
if len(datas) < limit:
break;
print('Fetch info end...')
answer_info.insert(0, title + '\n')
self.write2File(title + '.txt', answer_info)
def write2File(self, filePath, answerInfo):
print('Write info to file:Start...')
# 將文件內(nèi)容寫到文件中
with open(filePath, 'a', encoding='utf-8') as f:
f.writelines('\n\n')
for text in answerInfo:
f.writelines(text)
f.writelines('\n\n')
print('Write info to file:end...')
if __name__ == '__main__':
spider = ZhiHuSpider()
if spider.isLogin():
print('您已經(jīng)登錄')
else:
account = input('輸入賬號:')
secret = input('輸入密碼:')
spider.login(account, secret)
# spider.getQsAnswer('39162814')
# spider.getQsAnswer('57702309')
spider.getQsAnswer('49525749')
3. 總結(jié)
我注釋寫的那么詳細(xì),如果存在疑問,歡迎留言。