網絡爬蟲也稱爲網絡蜘蛛、網絡機器人,抓取網絡的數據。html
爬蟲分類python
1、通用網絡爬蟲:搜索引擎使用,遵照robots協議(君子協議)
robots協議 :網站經過robots協議告訴搜索引擎哪些頁面能夠抓取,哪些頁面不能抓取。https://www.taobao.com/robots.txt
2、聚焦網絡爬蟲 :本身寫的爬蟲程序數據庫
爬蟲爬取數據步驟瀏覽器
1、肯定須要爬取的URL地址
2、由請求模塊向URL地址發出請求,並獲得網站的響應
3、從響應內容中提取所需數據
1、所需數據,保存
2、頁面中有其餘須要繼續跟進的URL地址,繼續第2步去發請求,如此循環網絡
from urllib import request框架
request.urlopen() 向網站發起請求並獲取響應對象dom
參數:ide
響應對象(response)方法函數
from urllib import request url = 'http://www.baidu.com/' # 向百度發請求,獲得響應對象 response = request.urlopen(url) # 返回網頁源代碼 print(response.read().decode('utf-8')) # 返回http響應碼 print(response.getcode()) # 200 # 返回實際數據URL地址 print(response.geturl()) # http://www.baidu.com/
urllib.request.Request() 建立請求對象(包裝請求,重構User-Agent,使程序更像正常人類請求)測試
參數
使用流程
一、建立請求對象(重構User-Agent)
req = urllib.request.Request(url=url,headers={'User-Agent':'Mozilla/5.0 xxxx'})
二、請求對象發起請求,獲取響應對象(urlopen)
res = urllib.request.urlopen(req)
三、經過相應對象獲取響應內容
html = res.read().decode('utf-8')
from urllib import request url = 'http://httpbin.org/get' headers = {'User-Agent':'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)'} # 建立請求對象(包裝請求) req = request.Request(url=url,headers=headers) # 發請求,獲取響應對象 res = request.urlopen(req) # 讀取內容,返回網頁代碼 html = res.read().decode('utf-8') print(html)
URL地址中一個查詢參數
查詢參數:{'wd' : '美女'}
urlencode編碼後:'wd=%e7%be%8e%e5%a5%b3'
from urllib import parse url = 'http://www.baidu.com/s?' query_string = parse.urlencode({'wd':'美女'}) print(query_string) # wd=%E7%BE%8E%E5%A5%B3 url = url + query_string # http://www.baidu.com/wd=%E7%BE%8E%E5%A5%B3
URL地址中多個查詢參數
from urllib import parse query_string_dict = {'wd' : '美女', 'pn' : '50'} query_string = parse.urlencode(query_string_dict) url = 'http://www.baidu.com/s?{}'.format(query_string) print(url) # http://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3&pn=50
拼接URL地址的3種方式
1、字符串相加
'https://www.baidu.com/s?' + urlencode({'wd':'美女','pn':'50'})
2、字符串格式化(佔位符)
'https://www.baidu.com/s?%s' % urlencode({'wd':'美女','pn':'50'})
3、format()方法
'https://www.baidu.com/s?{}'.format(urlencode({'wd':'美女','pn':'50'}))
示例 在百度中輸入要搜索的內容,把響應內容保存到本地文件
from urllib import request from urllib import parse # 定義經常使用變量 word = input('請輸入搜索內容:') url = 'http://www.baidu.com/s?' headers = {'User-Agent':'Mozilla/5.0'} # url編碼,拼接完整URL query_string = parse.urlencode({'wd':word}) url = url + query_string # 三步走 req = request.Request(url=url,headers=headers) res = request.urlopen(req) html = res.read().decode('utf-8') filename = '{}.html'.format(word) with open(filename,'w',encoding='utf-8') as f: f.write(html)
from urllib import parse parse.quote('美女') # %E7%BE%8E%E5%A5%B3
from urllib import parse result = parse.unquote('%E7%BE%8E%E5%A5%B3') print(result) # 美女
實現步驟
一、找URL規律
一、不一樣吧
二、不一樣頁
第1頁:http://tieba.baidu.com/f?kw=????&pn=0
第2頁:http://tieba.baidu.com/f?kw=????&pn=50
第n頁:pn=(n-1)*50
二、獲取網頁內容
三、保存(本地文件、數據庫)
from urllib import request,parse import time import random class BaiduSpider(object): def __init__(self): self.url = 'http://tieba.baidu.com/f?kw={}&pn={}' self.headers = {'User-Agent':'Mozilla/5.0'} # 獲取響應 def get_page(self,url): req = request.Request(url=url,headers=self.headers) res = request.urlopen(req) html = res.read().decode('utf-8') return html # 保存數據 def write_page(self,filename,html): with open(filename,'w') as f: f.write(html) # 主函數 def main(self): name = input('請輸入貼吧名:') start = int(input('請輸入起始頁:')) end = int(input('請輸入終止頁:')) # 拼接URL地址,發請求 for page in range(start,end+1): pn = (page-1)*50 kw = parse.quote(name) # url編碼 url = self.url.format(kw,pn) html = self.get_page(url) # 獲取響應,並保存 filename = '{}-第{}頁.html'.format(name,page) self.write_page(filename,html) print('第{}頁爬取成功'.format(page)) # 提示進度 time.sleep(random.randint(1,3)) # 控制爬取速度 if __name__ == '__main__': spider = BaiduSpider() spider.main()