requests爬蟲組件

網絡爬蟲(又被稱爲網頁蜘蛛,網絡機器人,在FOAF社區中間,更常常的稱爲網頁追逐者),是一種按照必定的規則,自動地抓取萬維網信息的程序或者腳本。另一些不常使用的名字還有螞蟻、自動索引、模擬程序或者蠕蟲。html

Requests

Python標準庫中提供了:urllib、urllib二、httplib等模塊以供Http請求,可是,它的 API 太渣了。它是爲另外一個時代、另外一個互聯網所建立的。它須要巨量的工做,甚至包括各類方法覆蓋,來完成最簡單的任務。python

import urllib2 import json import cookielib def urllib2_request(url, method="GET", cookie="", headers={}, data=None): """ :param url: 要請求的url :param cookie: 請求方式,GET、POST、DELETE、PUT.. :param cookie: 要傳入的cookie,cookie= 'k1=v1;k1=v2' :param headers: 發送數據時攜帶的請求頭,headers = {'ContentType':'application/json; charset=UTF-8'} :param data: 要發送的數據GET方式須要傳入參數,data={'d1': 'v1'} :return: 返回元祖,響應的字符串內容 和 cookiejar對象 對於cookiejar對象,能夠使用for循環訪問: for item in cookiejar: print item.name,item.value """ if data: data = json.dumps(data) cookie_jar = cookielib.CookieJar() handler = urllib2.HTTPCookieProcessor(cookie_jar) opener = urllib2.build_opener(handler) opener.addheaders.append(['Cookie', 'k1=v1;k1=v2']) request = urllib2.Request(url=url, data=data, headers=headers) request.get_method = lambda: method response = opener.open(request) origin = response.read() return origin, cookie_jar # GET result = urllib2_request('http://127.0.0.1:8001/index/', method="GET") # POST result = urllib2_request('http://127.0.0.1:8001/index/', method="POST", data= {'k1': 'v1'}) # PUT result = urllib2_request('http://127.0.0.1:8001/index/', method="PUT", data= {'k1': 'v1'})
 

Requests 是使用 Apache2 Licensed 許可證的 基於Python開發的HTTP 庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得Pythoner進行網絡請求時,變得美好了許多,使用Requests能夠垂手可得的完成瀏覽器可有的任何操做。git

一、GET請求github

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 一、無參數實例
 
import requests
 
ret = requests.get( 'https://github.com/timeline.json' )
 
print ret.url
print ret.text
 
 
 
# 二、有參數實例
 
import requests
 
payload = { 'key1' : 'value1' , 'key2' : 'value2' }
ret = requests.get( "http://httpbin.org/get" , params = payload)
 
print ret.url
print ret.text

向 https://github.com/timeline.json 發送一個GET請求,將請求和響應相關均封裝在 ret 對象中。ajax

二、POST請求正則表達式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 一、基本POST實例
 
import requests
 
payload = { 'key1' : 'value1' , 'key2' : 'value2' }
ret = requests.post( "http://httpbin.org/post" , data = payload)
 
print ret.text
 
 
# 二、發送請求頭和數據實例
 
import requests
import json
 
url = 'https://api.github.com/some/endpoint'
payload = { 'some' : 'data' }
headers = { 'content-type' : 'application/json' }
 
ret = requests.post(url, data = json.dumps(payload), headers = headers)
 
print ret.text
print ret.cookies

向https://api.github.com/some/endpoint發送一個POST請求,將請求和相應相關的內容封裝在 ret 對象中。json

三、其餘請求api

1
2
3
4
5
6
7
8
9
10
requests.get(url, params = None , * * kwargs)
requests.post(url, data = None , json = None , * * kwargs)
requests.put(url, data = None , * * kwargs)
requests.head(url, * * kwargs)
requests.delete(url, * * kwargs)
requests.patch(url, data = None , * * kwargs)
requests.options(url, * * kwargs)
 
# 以上方法均是在此方法的基礎上構建
requests.request(method, url, * * kwargs)

requests模塊已經將經常使用的Http請求方法爲用戶封裝完成,用戶直接調用其提供的相應方法便可,其中方法的全部參數有:瀏覽器


 
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests >>> req = requests.request('GET', 'http://httpbin.org/get') <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others.  with sessions.Session() as session: return session.request(method=method, url=url, **kwargs)
 

更多requests模塊相關的文檔見:http://cn.python-requests.org/zh_CN/latest/服務器

自動登錄抽屜並點贊

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
### 一、首先登錄任何頁面,獲取cookie
 
i1 = requests.get(url = "http://dig.chouti.com/help/service" )
 
### 二、用戶登錄,攜帶上一次的cookie,後臺對cookie中的 gpsd 進行受權
i2 = requests.post(
     url = "http://dig.chouti.com/login" ,
     data = {
         'phone' : "86手機號" ,
         'password' : "密碼" ,
         'oneMonth' : ""
     },
     cookies = i1.cookies.get_dict()
)
 
### 三、點贊(只須要攜帶已經被受權的gpsd便可)
gpsd = i1.cookies.get_dict()[ 'gpsd' ]
i3 = requests.post(
     url = "http://dig.chouti.com/link/vote?linksId=8589523" ,
     cookies = { 'gpsd' : gpsd}
)
print (i3.text)

「破解」微信公衆號

「破解」微信公衆號其實就是使用Python代碼自動實現【登錄公衆號】->【獲取觀衆用戶】-> 【向關注用戶發送消息】。

注:只能向48小時內有互動的粉絲主動推送消息

一、自動登錄

分析對於Web登錄頁面,用戶登錄驗證時僅作了以下操做:

  • 登錄的URL:https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN
  • POST的數據爲:

        {
             'username': 用戶名,
             'pwd': 密碼的MD5值,
             'imgcode': "", 
             'f': 'json'
        }
    注:imgcode是須要提供的驗證碼,默認無需驗證碼,只有在屢次登錄未成功時,才須要用戶提供驗證碼才能登錄

  • POST的請求頭的Referer值,微信後臺用次來檢查是誰發送來的請求
  • 請求發送並登錄成功後,獲取用戶響應的cookie,之後操做其餘頁面時須要攜帶此cookie 
  • 請求發送並登錄成功後,獲取用戶相應的內容中的token
 
# -*- coding:utf-8 -*- import requests import time import hashlib def _password(pwd): ha = hashlib.md5() ha.update(pwd) return ha.hexdigest() def login(): login_dict = { 'username': "用戶名", 'pwd': _password("密碼"), 'imgcode': "", 'f': 'json' } login_res = requests.post( url= "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN", data=login_dict, headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'}) # 登錄成功以後獲取服務器響應的cookie resp_cookies_dict = login_res.cookies.get_dict() # 登錄成功後,獲取服務器響應的內容 resp_text = login_res.text # 登錄成功後,獲取token token = re.findall(".*token=(\d+)", resp_text)[0] print resp_text print token print resp_cookies_dict login()
 

登錄成功獲取的相應內容以下:

1
2
3
4
5
響應內容:
{ "base_resp" :{ "ret" : 0 , "err_msg" : "ok" }, "redirect_url" : "\/cgi-bin\/home?t=home\/index&lang=zh_CN&token=537908795" }
 
響應cookie:
{ 'data_bizuin' : '3016804678' , 'bizuin' : '3016804678' , 'data_ticket' : 'CaoX+QA0ZA9LRZ4YM3zZkvedyCY8mZi0XlLonPwvBGkX0/jY/FZgmGTq6xGuQk4H' , 'slave_user' : 'gh_5abeaed48d10' , 'slave_sid' : 'elNLbU1TZHRPWDNXSWdNc2FjckUxalM0Y000amtTamlJOUliSnRnWGRCdjFseV9uQkl5cUpHYkxqaGJNcERtYnM2WjdFT1pQckNwMFNfUW5fUzVZZnFlWGpSRFlVRF9obThtZlBwYnRIVGt6cnNGbUJsNTNIdTlIc2JJU29QM2FPaHZjcTcya0F6UWRhQkhO' }

二、訪問其餘頁面獲取用戶信息

分析用戶管理頁面,經過Pyhton代碼以Get方式訪問此頁面,分析響應到的 HTML 代碼,從中獲取用戶信息:

  • 獲取用戶的URL:https://mp.weixin.qq.com/cgi-bin/user_tag?action=get_all_data&lang=zh_CN&token=登錄時獲取的token
  • 發送GET請求時,須要攜帶登錄成功後獲取的cookie
    1
    { 'data_bizuin' : '3016804678' , 'bizuin' : '3016804678' , 'data_ticket' : 'C4YM3zZ...
  • 獲取當前請求的響應的html代碼
  • 經過正則表達式獲取html中的指定內容(Python的模塊Beautiful Soup)
  • 獲取html中每一個用戶的 data-fakeid屬性,該值是用戶的惟一標識,經過它可向用戶推送消息
 
# -*- coding:utf-8 -*- import requests import time import hashlib import json import re LOGIN_COOKIES_DICT = {} def _password(pwd): ha = hashlib.md5() ha.update(pwd) return ha.hexdigest() def login(): login_dict = { 'username': "用戶名", 'pwd': _password("密碼"), 'imgcode': "", 'f': 'json' } login_res = requests.post( url= "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN", data=login_dict, headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'}) # 登錄成功以後獲取服務器響應的cookie resp_cookies_dict = login_res.cookies.get_dict() # 登錄成功後,獲取服務器響應的內容 resp_text = login_res.text # 登錄成功後,獲取token token = re.findall(".*token=(\d+)", resp_text)[0] return {'token': token, 'cookies': resp_cookies_dict} def standard_user_list(content): content = re.sub('\s*', '', content) content = re.sub('\n*', '', content) data = re.findall("""cgiData=(.*);seajs""", content)[0] data = data.strip() while True: temp = re.split('({)(\w+)(:)', data, 1) if len(temp) == 5: temp[2] = '"' + temp[2] + '"' data = ''.join(temp) else: break while True: temp = re.split('(,)(\w+)(:)', data, 1) if len(temp) == 5: temp[2] = '"' + temp[2] + '"' data = ''.join(temp) else: break data = re.sub('\*\d+', "", data) ret = json.loads(data) return ret def get_user_list(): login_dict = login() LOGIN_COOKIES_DICT.update(login_dict) login_cookie_dict = login_dict['cookies'] res_user_list = requests.get( url= "https://mp.weixin.qq.com/cgi-bin/user_tag", params = {"action": "get_all_data", "lang": "zh_CN", "token": login_dict['token']}, cookies = login_cookie_dict, headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'} ) user_info = standard_user_list(res_user_list.text) for item in user_info['user_list']: print "%s %s " % (item['nick_name'],item['id'],) get_user_list()
 

三、發送消息

分析給用戶發送消息的頁面,從網絡請求中剖析獲得發送消息的URL,從而使用Python代碼發送消息:

  • 發送消息的URL:https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token=登錄時獲取的token放在此處&lang=zh_CN
  • 從登錄時相應的內容中獲取:token和cookie
  • 從用戶列表中獲取某個用戶惟一標識: fake_id
  • 封裝消息,併發送POST請求
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    send_dict = {
         'token' : 登錄時獲取的token,
         'lang' : "zh_CN" ,
         'f' : 'json' ,
         'ajax' : 1 ,
         'random' : "0.5322618900912392" ,
         'type' : 1 ,
         'content' : 要發送的內容,
         'tofakeid' : 用戶列表中獲取的用戶的 ID ,
         'imgcode' : ''
    }
 
# -*- coding:utf-8 -*- import requests import time import hashlib import json import re LOGIN_COOKIES_DICT = {} def _password(pwd): ha = hashlib.md5() ha.update(pwd) return ha.hexdigest() def login(): login_dict = { 'username': "用戶名", 'pwd': _password("密碼"), 'imgcode': "", 'f': 'json' } login_res = requests.post( url= "https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN", data=login_dict, headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'}) # 登錄成功以後獲取服務器響應的cookie resp_cookies_dict = login_res.cookies.get_dict() # 登錄成功後,獲取服務器響應的內容 resp_text = login_res.text # 登錄成功後,獲取token token = re.findall(".*token=(\d+)", resp_text)[0] return {'token': token, 'cookies': resp_cookies_dict} def standard_user_list(content): content = re.sub('\s*', '', content) content = re.sub('\n*', '', content) data = re.findall("""cgiData=(.*);seajs""", content)[0] data = data.strip() while True: temp = re.split('({)(\w+)(:)', data, 1) if len(temp) == 5: temp[2] = '"' + temp[2] + '"' data = ''.join(temp) else: break while True: temp = re.split('(,)(\w+)(:)', data, 1) if len(temp) == 5: temp[2] = '"' + temp[2] + '"' data = ''.join(temp) else: break data = re.sub('\*\d+', "", data) ret = json.loads(data) return ret def get_user_list(): login_dict = login() LOGIN_COOKIES_DICT.update(login_dict) login_cookie_dict = login_dict['cookies'] res_user_list = requests.get( url= "https://mp.weixin.qq.com/cgi-bin/user_tag", params = {"action": "get_all_data", "lang": "zh_CN", "token": login_dict['token']}, cookies = login_cookie_dict, headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'} ) user_info = standard_user_list(res_user_list.text) for item in user_info['user_list']: print "%s %s " % (item['nick_name'],item['id'],) def send_msg(user_fake_id, content='啥也沒發'): login_dict = LOGIN_COOKIES_DICT token = login_dict['token'] login_cookie_dict = login_dict['cookies'] send_dict = { 'token': token, 'lang': "zh_CN", 'f': 'json', 'ajax': 1, 'random': "0.5322618900912392", 'type': 1, 'content': content, 'tofakeid': user_fake_id, 'imgcode': '' } send_url = "https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token=%s&lang=zh_CN" % (token,) message_list = requests.post( url=send_url, data=send_dict, cookies=login_cookie_dict, headers={'Referer': 'https://mp.weixin.qq.com/cgi-bin/login?lang=zh_CN'} ) get_user_list() fake_id = raw_input('請輸入用戶ID:') content = raw_input('請輸入消息內容:') send_msg(fake_id, content)
 

以上就是「破解」微信公衆號的整個過程,經過Python代碼實現了自動【登錄微信公衆號平臺】【獲取用戶列表】【指定用戶發送消息】。

相關文章
相關標籤/搜索