一入爬蟲深似海,總結python爬蟲學習筆記!

正文

〇. python 基礎html

先放上python 3 的官方文檔:https://docs.python.org/3/ (看文檔是個好習慣)python

關於python 3 基礎語法方面的東西,網上有不少,你們能夠自行查找.正則表達式

一. 最簡單的爬取程序瀏覽器

爬取百度首頁源代碼:cookie

 

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

 

來看上面的代碼:python爬蟲

  • 對於python 3來講,urllib是一個很是重要的一個模塊 ,能夠很是方便的模擬瀏覽器訪問互聯網,對於python 3 爬蟲來講, urllib更是一個必不可少的模塊,它能夠幫助咱們方便地處理URL.
  • urllib.request是urllib的一個子模塊,能夠打開和處理一些複雜的網址

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,並返回一個 http.client.HTTPResponse對象,經過http.client.HTTPResponse的read()方法,得到response body,轉碼最後經過print()打印出來.

urllib.request.urlopen(urldata=None, [timeout, ]***, cafile=Nonecapath=Nonecadefault=Falsecontext=None)For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponseobject slightly modified.< 出自: https://docs.python.org/3/library/urllib.request.html >函數

  • decode('utf-8')用來將頁面轉換成utf-8的編碼格式,不然會出現亂碼

二 模擬瀏覽器爬取信息學習

在訪問某些網站的時候,網站一般會用判斷訪問是否帶有頭文件來鑑別該訪問是否爲爬蟲,用來做爲反爬取的一種策略。網站

先來看一下Chrome的頭信息(F12打開開發者模式)以下:

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

 

 

如圖,訪問頭信息中顯示了瀏覽器以及系統的信息(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庫.它可以經過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.

文檔中的例子其實說的已經比較清楚了,那下面就以爬取簡書首頁文章的標題一段代碼來演示一下:

先來看簡書首頁的源代碼:

一入爬蟲深似海,今後遊戲是路人!總結個人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解析器,還支持一些第三方的解析器,下表列出了主要的解析器,以及它們的優缺點:

 

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

 

四 將爬取的信息存儲到本地

以前咱們都是將爬取的數據直接打印到了控制檯上,這樣顯然不利於咱們對數據的分析利用,也不利於保存,因此如今就來看一下如何將爬取的數據存儲到本地硬盤。

1 對.txt文件的操做

讀寫文件是最多見的操做之一,python3 內置了讀寫文件的函數:open

open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None))Open file and return a corresponding file object. If the file cannot be opened, an OSErroris raised.

其中比較經常使用的參數爲filemode,參數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參數的含義見下表:

 

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

 

 

 

其中'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語句

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

 

2 圖片的儲存

有時候咱們的爬蟲不必定只是爬取文本數據,也會爬取一些圖片,下面就來看怎麼將爬取的圖片存到本地磁盤。

咱們先來選好目標,知乎話題:女生怎麼健身鍛造好身材? (單純由於圖多,不要多想哦 (# _ # ) )

看下頁面的源代碼,找到話題下圖片連接的格式,如圖:

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

 

 

能夠看到,圖片在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())

運行結果

一入爬蟲深似海,今後遊戲是路人!總結個人python爬蟲學習筆記!

相關文章
相關標籤/搜索