所謂爬蟲,就是按照必定的規則,自動的從網絡中抓取信息的程序或者腳本。萬維網就像一個巨大的蜘蛛網,咱們的爬蟲就是上面的一個蜘蛛,不斷的去抓取咱們須要的信息。html
一、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'))
帶參數的urllibpython
url = 'https://blog.csdn.net/weixin_43499626' url = url + '?' + key + '=' + value1 + '&' + key2 + '=' + value2
二、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'})
一、表單提交登陸
向服務器發送一個post請求並攜帶相關參數,將服務器返回的cookie保存在本地,cookie是服務器在客戶端上的「監視器」,記錄了登陸信息等。客戶端經過識別請求攜帶的cookie,肯定是否登陸mongodb
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)
二、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)
一、經過user-agent來控制訪問
user-agent可以使服務器識別出用戶的操做系統及版本、cpu類型、瀏覽器類型和版本。不少網站會設置user-agent白名單,只有在白名單範圍內的請求才能正常訪問。因此在咱們的爬蟲代碼中須要設置user-agent假裝成一個瀏覽器請求。有時候服務器還可能會校驗Referer,因此還可能須要設置Referer(用來表示此時的請求是從哪一個頁面連接過來的)json
# 設置請求頭信息 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
二、經過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))
三、設置請求間隔
import time time.sleep(1)
四、自動化測試工具Selenium
Web應用程序測試的Selenium工具。該工具能夠用於單元測試,集成測試,系統測試等等。它能夠像真正的用戶同樣去操做瀏覽器(包括字符填充、鼠標點擊、獲取元素、頁面切換),支持Mozilla Firefox、Google、Chrome、Safari、Opera、IE等等瀏覽器。
五、參數經過加密
某些網站可能會將參數進行某些加密,或者對參數進行拼接發送給服務器,以此來達到反爬蟲的目的。這個時候咱們能夠試圖經過js代碼,查看破解的辦法。
鏈接xxx
或者可使用"PhantomJS",PhantomJS是一個基於Webkit的"無界面"(headless)瀏覽器,它會把網站加載到內存並執行頁面上的JavaScript,由於不會展現圖形界面,因此運行起來比完整的瀏覽器更高效。
六、經過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以及各方向電子書