1. 程式人生 > >python3爬蟲 爬取圖片,爬取新聞網站文章並儲存到資料庫

python3爬蟲 爬取圖片,爬取新聞網站文章並儲存到資料庫

2017年9月16日零基礎入門Python,第二天就給自己找了一個任務,做網站文章的爬蟲小專案,因為實戰是學程式碼的最快方式。所以從今天起開始寫Python實戰入門系列教程,也建議大家學Python時一定要多寫多練。

目標

  • 1,學習Python爬蟲
  • 2,爬取新聞網站新聞列表
  • 3,爬取圖片
  • 4,把爬取到的資料存在本地資料夾或者資料庫
  • 5,學會用pycharm的pip安裝Python需要用到的擴充套件包

一,首先看看Python是如何簡單的爬取網頁的

1,準備工作

專案用的BeautifulSoup4和chardet模組屬於三方擴充套件包,如果沒有請自行pip安裝,我是用pycharm來做的安裝,下面簡單講下用pycharm安裝chardet和BeautifulSoup4

  • 在pycharm的設定裡按照下圖的步驟操作
    ![
    Uploading 2_085587.png ...]

  • 如下圖搜尋你要的擴充套件類庫,如我們這裡需要安裝chardet直接搜尋就行,然後點選install package, BeautifulSoup4做一樣的操作就行

2.png

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

3.png

二,由淺入深,我們先抓取網頁

# 簡單的網路爬蟲
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("全部抓取完成")

迫不及待的看下都爬取到了些什麼美圖

4.png

就這麼輕易的爬取到了24個妹子的圖片。是不是很簡單。

四,Python3爬取新聞網站新聞列表

  • 這裡我們只爬取新聞標題,新聞url,新聞圖片連結。
  • 爬取到的資料目前只做展示,等我學完Python操作資料庫以後會把爬取到的資料儲存到資料庫。

到這裡稍微複雜點,就分佈給大家講解
- 1 這裡我們需要先爬取到html網頁上面第一步有講怎麼抓取網頁
- 2分析我們要抓取的html標籤

5.png
分析上圖我們要抓取的資訊再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">
![](https://img.huxiucdn.com/article/cover/201708/22/173535862821.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214982.html" target="_blank" title="TFBOYS成員各自飛,商業價值天花板已現?">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/094856378420.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/213703.html" target="_blank" title="買手店江湖">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/122655034450.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214679.html" target="_blank" title="iPhone X正式告訴我們,手機和相機開始分道揚鑣">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/14/182151300292.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214962.html" target="_blank" title="信用已被透支殆盡,樂視汽車或成賈躍亭棄子">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/210518696352.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214867.html" target="_blank" title="別小看“搞笑諾貝爾獎”,要向好奇心致敬">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/15/180620783020.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214954.html" target="_blank" title="10 年前改變世界的,可不止有 iPhone | 發車">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/162049096015.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214908.html" target="_blank" title="感謝微博替我做主">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/010410913192.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/215001.html" target="_blank" title="蘋果確認取消打賞抽成,但還有多少內容讓你覺得值得掏腰包?">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/154147105217.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214969.html" target="_blank" title="中國音樂的“全面付費”時代即將到來?">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/17/101218317953.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</a>
</div>, <div class="hot-article-img">
<a href="/article/214964.html" target="_blank" title="百麗退市啟示錄:“一代鞋王”如何與新生代消費者漸行漸遠">
<!--視訊和圖片保留一個-->
![](https://img.huxiucdn.com/article/cover/201709/16/213400162818.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg)
</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資料庫操作以後,會寫一篇文章
《Python3實戰入門資料庫篇—把爬取到的資料存到資料庫》

敬請期待,

我也是剛自學Python,如果你也在自學Python,可以加我微信2501902696,大家一起學習,一起進步

相關推薦

python3爬蟲 圖片新聞網站文章儲存資料庫

2017年9月16日零基礎入門Python,第二天就給自己找了一個任務,做網站文章的爬蟲小專案,因為實戰是學程式碼的最快方式。所以從今天起開始寫Python實戰入門系列教程,也建議大家學Python時一定要多寫多練。 目標 1,學習Python爬蟲 2

關於LPL的微信文章存入資料庫

import requests from bs4 import BeautifulSoup import time import pymysql def get_HTML(url): hd = {'User-Agent': 'Mozilla/5.0'

Scrapy知名技術網站文章儲存到MySQL資料庫

之前的幾篇文章都是在講如何把資料爬下來,今天記錄一下把資料爬下來並儲存到MySQL資料庫。 文章中有講同步和非同步兩種方法。 所有文章文章的地址:http://blog.jobbole.com/all-posts/ 對所有文章

python3[爬蟲實戰] 使用seleniumxpath京東手機(上)

當然了,這個任務也是從QQ群裡面接過來的,主要是想提升自己的技術,一接過來是很開心的,但是,接完之後,寫了又寫,昨晚寫了3小時,前提晚上寫了2小時,搞的有些晚了,搞來搞去就卡在一個地方了,希望懂的大神們多幫忙指點一下, 使用selenium ,可能感覺用

Python3爬蟲系列:理論+實驗+妹子圖實戰

爬蟲系列: (1) 理論 (2) 實驗 (3) 實戰 1. 準備環境 1.1 安裝CentOS 1.2 安裝Python3 1.3 安裝MongoDB 嘗試使用motor實現

python爬蟲建立代理池5000個代理IP進行驗證!

前面已經介紹了urllib+正則表示式和BeautifulSoup進行爬取資料的方法,今天再解決一個實際問題——構建自己的代理池。     通過爬蟲在網上進行資料的獲取,由於效率很快,換言之,訪問的速度過快,導致一段時間內的流量過大,會使得對方的伺服器壓力過

PYTHON爬蟲——必應圖片關鍵詞

這段時間在實習,在做一些各大網站圖片爬取的工作,基本告一段落,現在分別對百度圖片,google圖片,並應(Bing)圖片三個網站的圖片搜尋結果進行爬取和下載。 首先通過爬蟲過程中遇到的問題,總結如下: 1、一次頁面載入的圖片數量各個網站是

python3爬蟲之使用Scrapy框架性感女神美女照片

使用Scrapy框架爬取性感女神美女照片其實很簡單哦,只需要5分鐘,爬取上萬張性感女神照片。 先給大家看一下成果吧: 激不激動,興不興奮,那就快來學一下吧: 開始專案前需要安裝python3和Scrapy,不會的自行百度,這裡就不具體介紹了 接下來是程式碼

python3爬蟲之使用Scrapy框架英雄聯盟高清桌面桌布

使用Scrapy爬蟲抓取英雄聯盟高清桌面桌布 開始專案前需要安裝python3和Scrapy,不會的自行百度,這裡就不具體介紹了 首先,建立專案 scrapy startproject loldesk 生成專案的目錄結構 首先需要定義抓取元素,在item.p

Python3爬蟲學習4:降的資訊儲存到本地

將爬取的資訊儲存到本地 之前我們都是將爬取的資料直接列印到了控制檯上,這樣顯然不利於我們對資料的分析利用,也不利於儲存,所以現在就來看一下如何將爬取的資料儲存到本地硬碟。 1.對.txt檔案的操作 讀寫檔案是最常見的操作之一,python3 內建了讀寫

python3指定百度貼吧頁面儲存成本地文件(批量貼吧頁面資料)

首先我們建立一個python檔案, tieba.py,我們要完成的是,輸入指定百度貼吧名字與指定頁面範圍之後爬取頁面html程式碼,我們首先觀察貼吧url的規律,比如: 發現規律了吧,貼吧中每個頁面不同之處,就是url最後的pn的值,其餘的都是一樣的,我們

Python爬蟲為何可以這麼叼?百度雲盤資源!儲存到自己雲盤

點選它,再點選右邊的【Cookies】就可以看到請求頭裡的 cookie 情況。cookie分析除了上面說到的兩個 cookie ,其他的請求頭引數可以參照手動轉存時抓包的請求頭。這兩個 cookie 預留出來做引數的原因是 cookie 都是有生存週期的,過期了需要更新,不同的賬號登入也有不同的 cooki

python3 爬蟲實戰 :用 Appium 抓手機 app 微信 的 資料

  From:https://blog.csdn.net/Fan_shui/article/details/81413595   本編教程從 appium 的環境配置開始,到抓取手機 app 微信朋友圈結束。 知乎:https://zhuanlan.zhihu.c

python 資訊文章儲存html及pdf格式

一、需求 研究生學長讓我把一個植物表型資訊系列文章的一系列文章爬下來儲存為pdf或者html格式。 首頁網址: https://mp.weixin.qq.com/s?__biz=MzI0Mjg5ODI1Ng==&mid=2247486022&idx=1&sn=

爬蟲與反爬蟲的較量-圖片

前言 補充 感覺 成功 轉行 限制 壁紙 coo 網站 前言 在去年6月吧,剛轉行做爬蟲的時候,經常拿圖片網還有小說網練手,無意中發現一個壁紙網站叫做娟娟壁紙網,有好多高清壁紙(這不是廣告,哈哈) 當時是寫了全站爬取的代碼。以為自己大工告成的時候,結果剛運行,就發現爬出

C#中向上向下

log () ceil 取整 mat math 示例 floor 向下取整 Math.Ceiling()向上取整,Math.Floor()向下取整 示例: d = 4.56789 string res = Math.Ceiling(Convert.ToDecimal(d))

python 向下向上四舍五入

int class nbsp bubuko alt div floor inf num # python 向下取整 floor 向上取整ceil 四舍五入 round import math num=3.1415926 # 向上取整 print(math.ceil(num

python3爬蟲 連結+表格+圖片(本地+csv+mongodb儲存

# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup import re import csv import time from pymongo import MongoClient client = Mon

python3爬蟲 連結+表格+圖片(本地+csv儲存

# -*- coding: utf-8 -*- import urllib.request import http.cookiejar from bs4 import BeautifulSoup import requests import csv import time import re i

PHP四捨五入整、向上整、向下整、小數擷取

PHP取整數函式常用的四種方法: 1.直接取整,捨棄小數,保留整數:intval();  2.四捨五入取整:round();  3.向上取整,有小數就加1:ceil();  4.向下取整:floor()。 一、intval—對變數轉成整數型態  int