python爬蟲-- 抓取網頁、圖片、文章
零基礎入門Python,給自己找了一個任務,做網站文章的爬蟲小專案,因為實戰是學程式碼的最快方式。所以從今天起開始寫Python實戰入門系列教程,也建議大家學Python時一定要多寫多練。
目標
- 1,學習Python爬蟲
- 2,爬取新聞網站新聞列表
- 3,爬取圖片
- 4,把爬取到的資料存在本地資料夾或者資料庫
- 5,學會用pycharm的pip安裝Python需要用到的擴充套件包
一,首先看看Python是如何簡單的爬取網頁的
1,準備工作
專案用的BeautifulSoup4和chardet模組屬於三方擴充套件包,如果沒有請自行pip安裝,我是用pycharm來做的安裝,下面簡單講下用pycharm安裝chardet和BeautifulSoup4
-
在pycharm的設定裡按照下圖的步驟操作
-
如下圖搜尋你要的擴充套件類庫,如我們這裡需要安裝chardet直接搜尋就行,然後點選install package, BeautifulSoup4做一樣的操作就行

- 安裝成功後就會出現在在安裝列表中,到此就說明我們安裝網路爬蟲擴充套件庫成功

二,由淺入深,我們先抓取網頁
我們這裡以抓取簡書首頁為例:www.jianshu.com/
# 簡單的網路爬蟲 from urllib import request import chardet response = request.urlopen("http://www.jianshu.com/") html = response.read() charset = chardet.detect(html)# {'language': '', 'encoding': 'utf-8', 'confidence': 0.99} html = html.decode(str(charset["encoding"]))# 解碼 print(html) 複製程式碼
由於抓取的html文件比較長,這裡簡單貼出來一部分給大家看下
<!DOCTYPE html> <!--[if IE 6]><html class="ie lt-ie8"><![endif]--> <!--[if IE 7]><html class="ie lt-ie8"><![endif]--> <!--[if IE 8]><html class="ie ie8"><![endif]--> <!--[if IE 9]><html class="ie ie9"><![endif]--> <!--[if !IE]><!--> <html> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"> <!-- Start of Baidu Transcode --> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta http-equiv="Cache-Control" content="no-transform" /> <meta name="applicable-device" content="pc,mobile"> <meta name="MobileOptimized" content="width"/> <meta name="HandheldFriendly" content="true"/> <meta name="mobile-agent" content="format=html5;url=http://localhost/"> <!-- End of Baidu Transcode --> <meta name="description"content="簡書是一個優質的創作社群,在這裡,你可以任性地創作,一篇短文、一張照片、一首詩、一幅畫……我們相信,每個人都是生活中的藝術家,有著無窮的創造力。"> <meta name="keywords"content="簡書,簡書官網,圖文編輯軟體,簡書下載,圖文創作,創作軟體,原創社群,小說,散文,寫作,閱讀"> ..........後面省略一大堆 複製程式碼
這就是Python3的爬蟲簡單入門,是不是很簡單,建議大家多敲幾遍
三,Python3爬取網頁裡的圖片並把圖片儲存到本地資料夾
目標
- 爬取百度貼吧裡的圖片
- 把圖片儲存到本地,都是妹子圖片奧 不多說,直接上程式碼,程式碼裡的註釋很詳細。大家仔細閱讀註釋就可以理解了
import re import urllib.request #爬取網頁html def getHtml(url): page = urllib.request.urlopen(url) html = page.read() return html html = getHtml("http://tieba.baidu.com/p/3205263090") html = html.decode('UTF-8') #獲取圖片連結的方法 def getImg(html): # 利用正則表示式匹配網頁裡的圖片地址 reg = r'src="([.*\S]*\.jpg)" pic_ext="jpeg"' imgre=re.compile(reg) imglist=re.findall(imgre,html) return imglist imgList=getImg(html) imgCount=0 #for把獲取到的圖片都下載到本地pic資料夾裡,儲存之前先在本地建一個pic資料夾 for imgPath in imgList: f=open("../pic/"+str(imgCount)+".jpg",'wb') f.write((urllib.request.urlopen(imgPath)).read()) f.close() imgCount+=1 print("全部抓取完成") 複製程式碼
迫不及待的看下都爬取到了些什麼美圖

就這麼輕易的爬取到了24個妹子的圖片。是不是很簡單。
四,Python3爬取新聞網站新聞列表
- 這裡我們只爬取新聞標題,新聞url,新聞圖片連結。
- 爬取到的資料目前只做展示,等我學完Python操作資料庫以後會把爬取到的資料儲存到資料庫。
到這裡稍微複雜點,就分佈給大家講解
- 1 這裡我們需要先爬取到html網頁上面第一步有講怎麼抓取網頁
- 2分析我們要抓取的html標籤

分析上圖我們要抓取的資訊再div中的a標籤和img標籤裡,所以我們要想的就是怎麼獲取到這些資訊
這裡就要用到我們匯入的BeautifulSoup4庫了,這裡的關鍵程式碼
# 使用剖析器為html.parser soup = BeautifulSoup(html, 'html.parser') # 獲取到每一個class=hot-article-img的a節點 allList = soup.select('.hot-article-img') 複製程式碼
上面程式碼獲取到的allList就是我們要獲取的新聞列表,抓取到的如下
[<div class="hot-article-img"> <a href="/article/211390.html" target="_blank">  </a> </div>, <div class="hot-article-img"> <a href="/article/214982.html" target="_blank" title="TFBOYS成員各自飛,商業價值天花板已現?"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/213703.html" target="_blank" title="買手店江湖"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214679.html" target="_blank" title="iPhone X正式告訴我們,手機和相機開始分道揚鑣"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214962.html" target="_blank" title="信用已被透支殆盡,樂視汽車或成賈躍亭棄子"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214867.html" target="_blank" title="別小看“搞笑諾貝爾獎”,要向好奇心致敬"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214954.html" target="_blank" title="10 年前改變世界的,可不止有 iPhone | 發車"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214908.html" target="_blank" title="感謝微博替我做主"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/215001.html" target="_blank" title="蘋果確認取消打賞抽成,但還有多少內容讓你覺得值得掏腰包?"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214969.html" target="_blank" title="中國音樂的“全面付費”時代即將到來?"> <!--視訊和圖片保留一個-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214964.html" target="_blank" title="百麗退市啟示錄:“一代鞋王”如何與新生代消費者漸行漸遠"> <!--視訊和圖片保留一個-->  </a> </div>] 複製程式碼
這裡資料是抓取到了,但是太亂了,並且還有很多不是我們想要的,下面就通過遍歷來提煉出我們的有效資訊
- 3 提取有效資訊
#遍歷列表,獲取有效資訊 for news in allList: aaa = news.select('a') # 只選擇長度大於0的結果 if len(aaa) > 0: # 文章連結 try:#如果丟擲異常就代表為空 href = url + aaa[0]['href'] except Exception: href='' # 文章圖片url try: imgUrl = aaa[0].select('img')[0]['src'] except Exception: imgUrl="" # 新聞標題 try: title = aaa[0]['title'] except Exception: title = "標題為空" print("標題",title,"\nurl:",href,"\n圖片地址:",imgUrl) print("==============================================================================================") 複製程式碼
這裡新增異常處理,主要是有的新聞可能沒有標題,沒有url或者圖片,如果不做異常處理,可能導致我們爬取的中斷。
過濾後的有效資訊
標題 標題為空 url: https://www.huxiu.com/article/211390.html 圖片地址: https://img.huxiucdn.com/article/cover/201708/22/173535862821.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 TFBOYS成員各自飛,商業價值天花板已現? url: https://www.huxiu.com/article/214982.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/17/094856378420.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 買手店江湖 url: https://www.huxiu.com/article/213703.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/17/122655034450.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 iPhone X正式告訴我們,手機和相機開始分道揚鑣 url: https://www.huxiu.com/article/214679.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/14/182151300292.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 信用已被透支殆盡,樂視汽車或成賈躍亭棄子 url: https://www.huxiu.com/article/214962.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/16/210518696352.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 別小看“搞笑諾貝爾獎”,要向好奇心致敬 url: https://www.huxiu.com/article/214867.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/15/180620783020.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 10 年前改變世界的,可不止有 iPhone | 發車 url: https://www.huxiu.com/article/214954.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/16/162049096015.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 感謝微博替我做主 url: https://www.huxiu.com/article/214908.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/16/010410913192.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 蘋果確認取消打賞抽成,但還有多少內容讓你覺得值得掏腰包? url: https://www.huxiu.com/article/215001.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/17/154147105217.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 中國音樂的“全面付費”時代即將到來? url: https://www.huxiu.com/article/214969.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/17/101218317953.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 標題 百麗退市啟示錄:“一代鞋王”如何與新生代消費者漸行漸遠 url: https://www.huxiu.com/article/214964.html 圖片地址: https://img.huxiucdn.com/article/cover/201709/16/213400162818.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 複製程式碼
到這裡我們抓取新聞網站新聞資訊就大功告成了,下面貼出來完整程式碼
from bs4 import BeautifulSoup from urllib import request import chardet url = "https://www.huxiu.com" response = request.urlopen(url) html = response.read() charset = chardet.detect(html) html = html.decode(str(charset["encoding"]))# 設定抓取到的html的編碼方式 # 使用剖析器為html.parser soup = BeautifulSoup(html, 'html.parser') # 獲取到每一個class=hot-article-img的a節點 allList = soup.select('.hot-article-img') #遍歷列表,獲取有效資訊 for news in allList: aaa = news.select('a') # 只選擇長度大於0的結果 if len(aaa) > 0: # 文章連結 try:#如果丟擲異常就代表為空 href = url + aaa[0]['href'] except Exception: href='' # 文章圖片url try: imgUrl = aaa[0].select('img')[0]['src'] except Exception: imgUrl="" # 新聞標題 try: title = aaa[0]['title'] except Exception: title = "標題為空" print("標題",title,"\nurl:",href,"\n圖片地址:",imgUrl) print("==============================================================================================") 複製程式碼
資料獲取到了我們還要把資料存到資料庫,只要存到我們的資料庫裡,資料庫裡有資料了,就可以做後面的資料分析處理,也可以用這些爬取來的文章,給app提供新聞api介面,當然這都是後話了,等我自學到Python資料庫操作以後,會寫一篇文章 ofollow,noindex">《Python3實戰入門資料庫篇---把爬取到的資料存到資料庫》