〇. python 基礎html
先放上python 3 的官方文檔:https://docs.python.org/3/ (看文檔是個好習慣)python
關於python 3 基礎語法方面的東西,網上有不少,你們能夠自行查找.正則表達式
一. 最簡單的爬取程序瀏覽器
爬取百度首頁源代碼:cookie
來看上面的代碼:python爬蟲
The urllib.requestmodule defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.less
urllib.request.urlopen(url, data=None, [timeout, ]***, cafile=None, capath=None, cadefault=False, context=None)For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponseobject slightly modified.< 出自: https://docs.python.org/3/library/urllib.request.html >函數
二 模擬瀏覽器爬取信息學習
在訪問某些網站的時候,網站一般會用判斷訪問是否帶有頭文件來鑑別該訪問是否爲爬蟲,用來做爲反爬取的一種策略。網站
先來看一下Chrome的頭信息(F12打開開發者模式)以下:
如圖,訪問頭信息中顯示了瀏覽器以及系統的信息(headers所含信息衆多,具體可自行查詢)
Python中urllib中的request模塊提供了模擬瀏覽器訪問的功能,代碼以下:
from urllib import request url = 'http://www.baidu.com' # page = request.Request(url) # page.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36') headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') print(page_info)
能夠經過add_header(key, value) 或者直接以參數的形式和URL一塊兒請求訪問,urllib.request.Request()
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
在學習中有迷茫不知如何學習的朋友小編推薦一個學Python的學習q u n 227 -435- 450能夠來了解一塊兒進步一塊兒學習!免費分享視頻資料
三 爬蟲利器Beautiful Soup
Beautiful Soup是一個能夠從HTML或XML文件中提取數據的Python庫.它可以經過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.
文檔中的例子其實說的已經比較清楚了,那下面就以爬取簡書首頁文章的標題一段代碼來演示一下:
先來看簡書首頁的源代碼:
能夠發現簡書首頁文章的標題都是在<a/>標籤中,而且class='title',因此,經過
find_all('a', 'title')
即可得到全部的文章標題,具體實現代碼及結果以下:
# -*- coding:utf-8 -*- from urllib import request from bs4 import BeautifulSoup url = r'http://www.jianshu.com' # 模擬真實瀏覽器進行訪問 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read() page_info = page_info.decode('utf-8') # 將獲取到的內容轉換成BeautifulSoup格式,並將html.parser做爲解析器 soup = BeautifulSoup(page_info, 'html.parser') # 以格式化的形式打印html # print(soup.prettify()) titles = soup.find_all('a', 'title') # 查找全部a標籤中class='title'的語句 # 打印查找到的每個a標籤的string for title in titles: print(title.string)
Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,下表列出了主要的解析器,以及它們的優缺點:
四 將爬取的信息存儲到本地
以前咱們都是將爬取的數據直接打印到了控制檯上,這樣顯然不利於咱們對數據的分析利用,也不利於保存,因此如今就來看一下如何將爬取的數據存儲到本地硬盤。
1 對.txt文件的操做
讀寫文件是最多見的操做之一,python3 內置了讀寫文件的函數:open
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None))Open file and return a corresponding file object. If the file cannot be opened, an OSErroris raised.
其中比較經常使用的參數爲file和mode,參數file爲文件的路徑,參數mode爲操做文件的方式(讀/寫),函數的返回值爲一個file對象,若是文件操做出現異常的話,則會拋出 一個OSError
還以簡書首頁文章題目爲例,將爬取到的文章標題存放到一個.txt文件中,具體代碼以下:
# -*- coding:utf-8 -*- from urllib import request from bs4 import BeautifulSoup url = r'http://www.jianshu.com' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') soup = BeautifulSoup(page_info, 'html.parser') titles = soup.find_all('a', 'title') try: # 在E盤以只寫的方式打開/建立一個名爲 titles 的txt文件 file = open(r'E: itles.txt', 'w') for title in titles: # 將爬去到的文章題目寫入txt中 file.write(title.string + ' ') finally: if file: # 關閉文件(很重要) file.close()
open中mode參數的含義見下表:
其中't'爲默認模式,'r'至關於'rt',符號能夠疊加使用,像'r+b'
另外,對文件操做必定要注意的一點是:打開的文件必定要關閉,不然會佔用至關大的系統資源,因此對文件的操做最好使用try:...finally:...的形式。可是try:...finally:...的形式會使代碼顯得比較雜亂,所幸python中的with語句能夠幫咱們自動調用close()而不須要咱們寫出來,因此,上面代碼中的try:...finally:...可以使用下面的with語句來代替:
with open(r'E: itle.txt', 'w') as file: for title in titles: file.write(title.string + ' ')
效果是同樣的,建議使用with語句
2 圖片的儲存
有時候咱們的爬蟲不必定只是爬取文本數據,也會爬取一些圖片,下面就來看怎麼將爬取的圖片存到本地磁盤。
咱們先來選好目標,知乎話題:女生怎麼健身鍛造好身材? (單純由於圖多,不要多想哦 (# _ # ) )
看下頁面的源代碼,找到話題下圖片連接的格式,如圖:
能夠看到,圖片在img標籤中,且class=origin_image zh-lightbox-thumb,並且連接是由.jpg結尾,咱們即可以用Beautiful Soup結合正則表達式的方式來提取全部連接,以下:
links = soup.find_all('img', "origin_image zh-lightbox-thumb",src=re.compile(r'.jpg$'))
提取出全部連接後,使用request.urlretrieve來將全部連接保存到本地
Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers)where filename is the local file name under which the object can be found, and headers is whatever the info()method of the object returned by urlopen()returned (for a remote object). Exceptions are the same as for urlopen().
具體實現代碼以下:
# -*- coding:utf-8 -*- import time from urllib import request from bs4 import BeautifulSoup import re url = r'https://www.zhihu.com/question/22918070' headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'} page = request.Request(url, headers=headers) page_info = request.urlopen(page).read().decode('utf-8') soup = BeautifulSoup(page_info, 'html.parser') # Beautiful Soup和正則表達式結合,提取出全部圖片的連接(img標籤中,class=**,以.jpg結尾的連接) links = soup.find_all('img', "origin_image zh-lightbox-thumb",src=re.compile(r'.jpg$')) # 設置保存的路徑,不然會保存到程序當前路徑 local_path = r'E:Pic' for link in links: print(link.attrs['src']) # 保存連接並命名,time防止命名衝突 request.urlretrieve(link.attrs['src'], local_path+r'%s.jpg' % time.time())
運行結果