Python爬蟲入門這一篇就夠了
何謂爬蟲
所謂爬蟲,就是按照一定的規則,自動的從網路中抓取資訊的程式或者指令碼。全球資訊網就像一個巨大的蜘蛛網,我們的爬蟲就是上面的一個蜘蛛,不斷的去抓取我們需要的資訊。
爬蟲三要素
- 抓取
- 分析
- 儲存
基礎的抓取操作
1、urllib
在Python2.x中我們可以通過urllib 或者urllib2 進行網頁抓取,但是再Python3.x 移除了urllib2。只能通過urllib進行操作
import urllib.request response = urllib.request.urlopen('https://blog.csdn.net/weixin_43499626') print(response.read().decode('utf-8'))
帶引數的urllib
url = 'https://blog.csdn.net/weixin_43499626' url = url + '?' + key + '=' + value1 + '&' + key2 + '=' + value2
2、requests
requests庫是一個非常實用的HTPP客戶端庫,是抓取操作最常用的一個庫。Requests庫滿足很多需求
import requests # get請求 response = requests.get(url='https://blog.csdn.net/weixin_43499626') print(response.text)#列印解碼後的返回資料 # 帶引數的requests get請求 response = requests.get(url='https://blog.csdn.net/weixin_43499626', params={'key1':'value1', 'key2':'value2'})
需要登入的情況下
1、表單提交登入
向伺服器傳送一個post請求並攜帶相關引數,將伺服器返回的cookie儲存在本地,cookie是伺服器在客戶端上的“監視器”,記錄了登入資訊等。客戶端通過識別請求攜帶的cookie,確定是否登入
params = {'username': 'root', 'passwd': 'root'} response = requests.post("http:xxx.com/login", data=params) for key,value in response.cookies.items(): print('key = ', key + ' ||| value :'+ value)
2、cookie登入
我們可以將登入的cookie儲存在檔案中,
import urllib.request import http.cookiejar """ 儲存登入的cookie """ """ MozillaCookieJar : cookiejar的子類 從FileCookieJar派生而來,建立與Mozilla瀏覽器 cookies.txt相容的FileCookieJar例項。 """ cookie = http.cookiejar.MozillaCookieJar('cookie.txt') # 構建一個cookie的處理器 handler = urllib.request.HTTPCookieProcessor(cookie) # 獲取一個opener物件 opener = urllib.request.build_opener(handler) # # 獲取一個請求物件 request = urllib.request.Request('http://flights.ctrip.com/',headers={"Connection": "keep-alive"}) # 請求伺服器,獲取響應物件。cookie會在response裡一起響應 response = opener.open(request) # 儲存cookie到檔案 cookie.save(ignore_discard=True, ignore_expires=True) """ 請求攜帶檔案中的cookie """ import urllib.request import http.cookiejar cookie = http.cookiejar.MozillaCookieJar() cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True) handler = urllib.request.HTTPCookieProcessor(cookie) opener = urllib.request.build_opener(handler) request = urllib.request.Request('http://flights.ctrip.com/') html = opener.open(request).read().decode('gbk') print(html)
常見的反爬有哪些
1、通過user-agent來控制訪問
user-agent能夠使伺服器識別出使用者的作業系統及版本、cpu型別、瀏覽器型別和版本。很多網站會設定user-agent白名單,只有在白名單範圍內的請求才能正常訪問。所以在我們的爬蟲程式碼中需要設定user-agent偽裝成一個瀏覽器請求。有時候伺服器還可能會校驗Referer,所以還可能需要設定Referer(用來表示此時的請求是從哪個頁面連結過來的)
# 設定請求頭資訊 headers = { 'Host': 'https://blog.csdn.net', 'Referer': 'https://blog.csdn.net/weixin_43499626/article/details/85875090', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' } response = requests.get("http://www.baidu.com", headers=headers)
如下是CSDN中的Request Header中的資訊
accept: */* accept-encoding: gzip, deflate, br accept-language: zh-CN,zh;q=0.9 content-length: 0 cookie: bdshare_firstime=1500xxxxxxxx.............. origin: https://blog.csdn.net referer: https://blog.csdn.net/weixin_43499626/article/details/85875090 user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36 x-requested-with: XMLHttpRequest
2、通過IP來限制
當我們用同一個ip多次頻繁訪問伺服器時,伺服器會檢測到該請求可能是爬蟲操作。因此就不能正常的響應頁面的資訊了。
解決辦法常用的是使用IP代理池。網上就有很多提供代理的網站、
proxies = { "http": "http://119.101.125.56", "https": "http://119.101.125.1", } response = requests.get("http://www.baidu.com", proxies=random.choices(proxies))
3、設定請求間隔
import time time.sleep(1)
4、自動化測試工具Selenium
Web應用程式測試的Selenium工具。該工具可以用於單元測試,整合測試,系統測試等等。它可以像真正的使用者一樣去操作瀏覽器(包括字元填充、滑鼠點選、獲取元素、頁面切換),支援Mozilla Firefox、Google、Chrome、Safari、Opera、IE等等瀏覽器。
5、引數通過加密
某些網站可能會將引數進行某些加密,或者對引數進行拼接傳送給伺服器,以此來達到反爬蟲的目的。這個時候我們可以試圖通過js程式碼,檢視破解的辦法。
連線xxx
或者可以使用"PhantomJS",PhantomJS是一個基於Webkit的"無介面"(headless)瀏覽器,它會把網站載入到記憶體並執行頁面上的JavaScript,因為不會展示圖形介面,所以執行起來比完整的瀏覽器更高效。
6、通過robots.txt來限制爬蟲
robots.txt是一個限制爬蟲的規範,該檔案是用來宣告哪些東西不能被爬取。如果根目錄存在該檔案,爬蟲就會按照檔案的內容來爬取指定的範圍。
瀏覽器訪問https://www.taobao.com/robots.txt
可以檢視淘寶的robots.txt檔案
部分內容如下
User-agent:Baiduspider Disallow:/product/ Disallow:/ User-Agent:Googlebot Disallow:/ User-agent:Bingbot Disallow:/ User-Agent:360Spider Disallow:/ User-Agent:Yisouspider Disallow:/ User-Agent:Sogouspider Disallow:/ User-Agent:Yahoo!Slurp Disallow:/ User-Agent:* Disallow:/
可以看出淘寶拒絕了百度爬蟲、谷歌爬蟲、必應爬蟲、360爬蟲、神馬爬蟲,搜狗爬蟲、雅虎爬蟲等約束。
分析
我們可以分析爬取的網頁內容,獲得我們真正需要的資料,常用的有正則表示式,BeautifulSoup,XPath、lxml等
正則表示式是進行內容匹配,將符合要求的內容全部獲取;
xpath()能將字串轉化為標籤,它會檢測字串內容是否為標籤,但是不能檢測出內容是否為真的標籤;
Beautifulsoup是Python的一個第三方庫,它的作用和 xpath 作用一樣,都是用來解析html資料的相比之下,xpath的速度會快一點,因為xpath底層是用c來實現的
儲存
通過分析網頁內容,獲取到我們想要的資料,我們可以選擇存到文字檔案中,亦可以儲存在資料庫中,常用的資料庫有MySql、MongoDB
儲存為json檔案
import json dictObj = { '小明':{ 'age': 15, 'city': 'beijing', }, '湯姆': { 'age': 16, 'city': 'guangzhou', } } jsObj = json.dumps(dictObj, ensure_ascii=False) fileObject = open('jsonFile.json', 'w') fileObject.write(jsObj) fileObject.close()
儲存為cvs檔案
import csv with open('student.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['姓名', '年齡', '城市']) writer.writerows([['小明', 15 , '北京'],['湯姆', 16, '廣州']])
儲存到Mongo
# mongo服務 client = pymongo.MongoClient('mongodb://127.0.0.1:27017/') # test資料庫 db = client.test # student表,沒有自動建立 student_db = db.student student_json = { 'name': '小明', 'age': 15, 'city': '北京' } student_db.insert(student_json)
歡迎關注我的公眾號:程式設計師共成長
公眾號內回覆【禮包】,獲取程式設計師專屬資料,包括但不限於Java、Python、Linux、資料庫、大資料、架構、測試、前端、ui以及各方向電子書