python學習之爬蟲一

來源:互聯網
上載者:User

標籤:最大   使用   hub   操作   gecko   inpu   tps   net   bs4   

一,爬蟲原理:

通過類比瀏覽器的行為 自動從網上獲得需要的資料

 

二,爬蟲的流程

1,發送request請求給某個URL :

2,獲得返回的response 解析 得到需要的資料 再根據自己的需要進行各種處理

 

三,具體的實現代碼 

3.1發送request請求分2種:get 和 post  ,這裡使用的是python3 使用的模組是requests ,可使用pip3 install requests(pip也行 只要你的python安裝目錄下的scripts檔案夾裡既有pip.exe 又有pip3.exe) 下載並安裝

3.1.1

get請求:

get請求的參數一般有個URL就夠了 

樣本:

import requestsURL = ‘https://github.com/login‘r1 = requests.get(URL)  # 用變數r1接收response
 

3.1.2

post請求:

post請求一般用於向服務端提交資料 比如登入賬戶 點贊 

post請求的參數比較多 一般包括url=‘‘ , headers={}, data={}, cookies={}

其中headers是要提交的要求標頭 一般至少包括:uesr-Agent裝置資訊  

data是請求體 一般至少包括: user帳號 password密碼  有時要有token(用於驗證是否是瀏覽器行為 一種反爬蟲手段)

cookies 一種最常見的驗證方式 即反爬方式

具體的某個請求瀏覽器發送了哪些資訊可以到瀏覽器的network裡面找 最大限度的類比瀏覽器向URL發送請求

樣本:

1 r2 = requests.post(2     url=‘https://github.com/session‘,3     data={‘login‘: ‘xxx‘, ‘password‘: ‘xxx‘, ‘authenticity_token‘: token},4     cookies=r1_cookies_dict,5     headers={‘User-Agent‘:6             ‘Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36‘}7                    )
View Code

3.2 獲得返回的response 階段

3.2.1

對於返回的r1以下幾種操作:

# r1.content   # 原始的位元組類型的內容# r1.text   # 字串型的內容# r1.cookies.get_dict()  # 獲得返回的cookies並將其轉成dict類型# print(r1.apparent_encoding)  # 獲得返回內容的編碼# r1.encoding=‘utf-8‘  # 將編碼設定為‘utf-8‘# r1.encoding=r1.apparent_encoding   # 將編碼設為返回來的編碼

3.2.2

用BeautifulSoup模組來提取response中的資料

下載並安裝 pip install beatifulsoup4

匯入模組的方式要注意 :

from bs4 import BeautifulSoup

使用模組的find和find_all方法來獲得資料:

find 找到並返回第一個對象

find_all 找到所有的對象並打包成一個列表返回

樣本:

import requestsfrom bs4 import BeautifulSoupURL = ‘https://github.com/login‘r1 = requests.get(URL)# 注意參數為字串形式(.text),使用了內建解析器‘html.parser‘也有第三方的解析器‘lxml‘s1 = BeautifulSoup(r1.text, ‘html.parser‘)# 通過find方法找到一個name屬性為特定值的input標籤的value屬性的值tag_input = s1.find(‘input‘, attrs={‘name‘: ‘authenticity_token‘})token = tag_input.get(‘value‘)# 獲得返回的cookiesr1_cookies_dict = r1.cookies.get_dict()

 

四,一個作業的完整樣本:帳號密碼我用xxx來代替了

‘‘‘自動登入GitHub帳號,並列印name schoolwriten by Zhao Shuaiqq:123456789‘‘‘import requestsfrom bs4 import BeautifulSoup# 訪問github登入頁URL = ‘https://github.com/login‘r1 = requests.get(URL)# r1.content# r1.text# r1.cookies.get_dict()# print(r1.apparent_encoding)# r1.encoding=‘utf-8‘# r1.encoding=r1.apparent_encoding# print(r1.text)   # 驗證 此get請求成功獲得傳回值# 先找到返回過來的tokens1 = BeautifulSoup(r1.text, ‘html.parser‘)# tag_div = s1.find(name=‘div‘, id=‘login‘)  # 這裡有個坑 不要先找這個div再找裡面的hidden input 找不到 要直接找input# print(tag_div)  # 這裡能正確列印 但不是我們要的內容tag_input = s1.find(‘input‘, attrs={‘name‘: ‘authenticity_token‘})# 到這裡為止並沒有獲得我要的那個單獨的input 而是一堆東西 不過並不影響我獲得該隱藏input下的token值 不知道為什麼?# print(tag_input.get(‘value‘))   # 成功獲得tokentoken = tag_input.get(‘value‘)# 獲得cookiesr1_cookies_dict = r1.cookies.get_dict()# print(r1_cookies_dict)# 輸入賬戶資訊 帶上token 登入r2 = requests.post(    url=‘https://github.com/session‘,    data={‘login‘: ‘xxx‘, ‘password‘: ‘xxx‘, ‘authenticity_token‘: token},    cookies=r1_cookies_dict,    headers={‘User-Agent‘:            ‘Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36‘}                   )# print(r2.text)  # 驗證 帶上cookies 並且在data中帶上token 帳號 密碼 正確的話 成功登入# 進入我的個人資訊頁面r3 = requests.get(‘https://github.com/gazs2005‘)soup = BeautifulSoup(r3.text, ‘html.parser‘)name = soup.find(‘span‘, attrs={‘itemprop‘: ‘name‘}).textschool = soup.find(‘span‘, class_=‘p-org‘).find(‘div‘).textprint(‘name:%s‘ % name)print(‘school:%s‘ % school)
View Code

最後成功的將我的github賬戶的暱稱(name)和工作單位(school)列印出來  當然工作單位是亂寫的

 

五,學習心得:

爬蟲的本質就是用代碼類比瀏覽器的行為 所以要對瀏覽器的行為有所瞭解 這就涉及到web前 後端的知識 這些知識我都不懂  所以 感覺如果要學好爬蟲的話 還有很長的路要走啊 

要善用瀏覽器中的‘檢查’裡的各種功能(比如 Elements Network)來獲得資訊 以便最大限度的模仿瀏覽器的行為

python學習之爬蟲一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.