Python開發大師總結出了超級詳細的Python爬蟲學習清單,免費教程

0. Python 基礎

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

關於Python 3 基礎語法方面的東西,網上有很多,大家可以自行查找.

一. 最簡單的爬取程序

爬取百度首頁源代碼:

來看上面的代碼:

對於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.

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的同學,大家可以+下Python學習分享裙:五二八 三九七 六一七,即可免費領取一整套系統的 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)

三 爬蟲利器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(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參數的含義見下表:

其中'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())

2019年最新python教程

如果你處於想學Python或者正在學習Python,Python的教程不少了吧,但是是最新的嗎?

說不定你學了可能是兩年前人家就學過的內容,在這小編分享一波2019最新的python全套教程最後小編爲大家準備了9月份新出的Python自學視頻教程,共計約200G,免費分享給大家!需要的在評論區留言。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章