路飛學城-Python爬蟲實戰密訓-第1章
阿新 • • 發佈:2018-07-05
hidden 正則 lec color cookie pass __name__ 課程 type
正式的開始學習爬蟲知識,Python是一門接觸就會愛上的語言。路飛的課真的很棒,課程講解不是告訴你結論,而是在告訴你思考的方法和過程。
第一章,學習了如何爬取汽車之家以及抽屜登錄並點贊。
1 import requests 2 from bs4 import BeautifulSoup 3 4 5 # 登錄github並返回帳戶名稱 6 def get_info(user_name, user_password): 7 headers = { 8 ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36‘ 9 ‘(KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36‘} 10 try: 11 # 獲取cookie及token信息 12 ret = requests.get( 13 url=‘https://github.com/login‘, 14 headers=headers 15 ) 16 cookie_dict1 = ret.cookies.get_dict() 17 res = BeautifulSoup(ret.text, ‘html.parser‘) 18 token = res.find(name=‘input‘, attrs={‘type‘: ‘hidden‘, ‘name‘: ‘authenticity_token‘}).get(‘value‘) 19 # 請求頭,完成github登錄 20 ret2 = requests.post( 21 url=‘https://github.com/session‘, 22 data={ 23 ‘commit‘: ‘Sign in‘, 24 ‘utf8‘: ‘?‘, 25 ‘authenticity_token‘: token, 26 ‘login‘: user_name, 27 ‘password‘: user_password 28 }, 29 headers=headers, 30 cookies=cookie_dict1 31 ) 32 cookie_dict2 = ret2.cookies.get_dict() 33 # 獲取用戶信息數據 34 ret3 = requests.get( 35 url=‘https://github.com/‘+user_name, 36 headers=headers, 37 cookies=cookie_dict2 38 ) 39 res3 = BeautifulSoup(ret3.text, ‘html.parser‘) 40 div = res3.find(name=‘div‘, attrs={‘id‘: ‘js-pjax-container‘}) 41 h1 = div.find(name=‘h1‘, attrs={‘class‘: ‘vcard-names‘}) 42 name = h1.find(name=‘span‘, attrs={‘class‘: ‘p-name vcard-fullname d-block overflow-hidden‘}).get_text() 43 print(‘The user name is:%s‘ % name) 44 a = div.find(name=‘a‘, attrs={‘class‘: ‘u-photo d-block tooltipped tooltipped-s‘}) 45 img = a.find(name=‘img‘, attrs={‘class‘: ‘avatar width-full rounded-2‘}).get(‘src‘) 46 print(‘The user photo address is:%s‘ % img) 47 except: 48 print(‘sorry,cannot get the information‘) 49 50 51 if __name__ == ‘__main__‘: 52 user_name = input(‘Please input your login name:‘).strip() 53 user_password = input(‘Please input your password:‘).strip() 54 get_info(user_name, user_password)
1. 爬蟲本質,通過代碼偽造瀏覽器發送請求;
2. Http請求偽造像不像:
——請求頭:
—— user-agent:代指用戶使用的是什麽設備訪問
—— cookie:在用戶瀏覽器上保存的標記
——請求體:
—— name=xxxx&age=18
—— {‘name’:’xxxx’,’age’:18}
拿不到數據,要麽請求頭有問題,要麽請求體有問題
3. 分析Http請求
—— 先看XHR(ajax請求)
—— 查看是Get還是Post請求
—— Post請求要看請求數據格式,註意找Token、Cookies
—— 可以用正則,或者BS4 selector解析想要的數據
路飛學城-Python爬蟲實戰密訓-第1章