python入門之爬蟲篇 爬取圖片,文章,網頁

一,首先看看Python是如何簡單的爬取網頁的
1,準備工做
項目用的BeautifulSoup4和chardet模塊屬於三方擴展包,若是沒有請自行pip安裝,我是用pycharm來作的安裝,下面簡單講下用pycharm安裝chardet和BeautifulSoup4

html

在pycharm的設置裏按照下圖的步驟操做
在這裏插入圖片描述
以下圖搜索你要的擴展類庫,如咱們這裏須要安裝chardet直接搜索就行,而後點擊install package, BeautifulSoup4作同樣的操做就行
在這裏插入圖片描述
安裝成功後就會出如今在安裝列表中,到此就說明咱們安裝網絡爬蟲擴展庫成功
在這裏插入圖片描述
二,由淺入深,咱們先抓取網頁
咱們這裏以抓取簡書首頁爲例:http://www.jianshu.com/
在這裏插入圖片描述
因爲抓取的html文檔比較長,這裏簡單貼出來一部分給你們看下








html5

1.<!DOCTYPE html>
2.<!--[if IE 6]><html class="ie lt-ie8"><![endif]-->
3.<!--[if IE 7]><html class="ie lt-ie8"><![endif]-->
4.<!--[if IE 8]><html class="ie ie8"><![endif]-->
5.<!--[if IE 9]><html class="ie ie9"><![endif]-->
6.<!--[if !IE]><!--> <html> <!--<![endif]-->
7.
8.<head>
9. <meta charset="utf-8">
10. 10.<meta http-equiv="X-UA-Compatible" content="IE=Edge">
11.<meta name="viewport" content="width=device-width, initial-scale=1.0,user
      scalable=no">
12.
13.<!-- Start of Baidu Transcode -->
14.<meta http-equiv="Cache-Control" content="no-siteapp" />
15.<meta http-equiv="Cache-Control" content="no-transform" />
11. <meta name="applicable-device" content="pc,mobile">
17.<meta name="MobileOptimized" content="width"/>
18.<meta name="HandheldFriendly" content="true"/>
19.<meta name="mobile-agent" content="format=html5;url=http://localhost/">
20.<!-- End of Baidu Transcode -->
21.
12.    <meta name="description"  content="簡書是一個優質的創做社區,在這裏,你能夠任性地創做,一篇短文、一張照片、一首詩、一幅畫……咱們相信,每一個人都是生活中的藝術家,有着無窮的創造力。">
23.<meta name="keywords"  content="簡書,簡書官網,圖文編輯軟件,簡書下載,圖文創做,創做軟件,原創社區,小說,散文,寫做,閱讀">
24...........後面省略一大堆

這就是Python3的爬蟲簡單入門,是否是很簡單,建議你們多敲幾遍python

三,Python3爬取網頁裏的圖片並把圖片保存到本地文件夾
目標
數據庫

爬取百度貼吧裏的圖片
把圖片保存到本地,都是妹子圖片奧
很少說,直接上代碼,代碼裏的註釋很詳細。你們仔細閱讀註釋就能夠理解了
在這裏插入圖片描述
火燒眉毛的看下都爬取到了些什麼美圖



api

在這裏插入圖片描述
就這麼輕易的爬取到了24個妹子的圖片。是否是很簡單。
網絡

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

這裏咱們只爬取新聞標題,新聞url,新聞圖片連接。
爬取到的數據目前只作展現,等我學完Python操做數據庫之後會把爬取到的數據保存到數據庫。
到這裏稍微複雜點,就分佈給你們講解

網站

1 這裏咱們須要先爬取到html網頁上面第一步有講怎麼抓取網頁
2分析咱們要抓取的html標籤
ui

在這裏插入圖片描述
分析上圖咱們要抓取的信息再div中的a標籤和img標籤裏,因此咱們要想的就是怎麼獲取到這些信息
編碼

這裏就要用到咱們導入的BeautifulSoup4庫了,這裏的關鍵代碼
在這裏插入圖片描述
上面代碼獲取到的allList就是咱們要獲取的新聞列表,抓取到的以下

1.[<div class="hot-article-img">
2.<a href="/article/211390.html" target="_blank">
3.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA4LzIyLzE3MzUzNTg2MjgyMS5qcGc?x-oss-process=image/format,png)
4.</a>
5.</div>, <div class="hot-article-img">
6.<a href="/article/214982.html" target="_blank" title="TFBOYS成員各自飛,商業價值天花板已現?">
7.<!--視頻和圖片保留一個-->
8.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE3LzA5NDg1NjM3ODQyMC5qcGc?x-oss-process=image/format,png)
9.</a>
10.</div>, <div class="hot-article-img">
11.<a href="/article/213703.html" target="_blank" title="買手店江湖">
12.<!--視頻和圖片保留一個-->
13.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE3LzEyMjY1NTAzNDQ1MC5qcGc?x-oss-process=image/format,png)
14.</a>
15.</div>, <div class="hot-article-img">
16<a href="/article/214679.html" target="_blank" title="iPhone X正式告訴咱們,手機和相機開始分道揚鑣">
17.<!--視頻和圖片保留一個-->
18.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE0LzE4MjE1MTMwMDI5Mi5qcGc?x-oss-process=image/format,png)
19.</a>
20.</div>, <div class="hot-article-img">
21.<a href="/article/214962.html" target="_blank" title="信用已被透支殆盡,樂視汽車或成賈躍亭棄子">
22.<!--視頻和圖片保留一個-->
23.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE2LzIxMDUxODY5NjM1Mi5qcGc?x-oss-process=image/format,png)
24.</a>
25.</div>, <div class="hot-article-img">
26.<a href="/article/214867.html" target="_blank" title="別小看「搞笑諾貝爾獎」,要向好奇心致敬">
27.<!--視頻和圖片保留一個-->
28.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE1LzE4MDYyMDc4MzAyMC5qcGc?x-oss-process=image/format,png)
29.</a>
30.</div>, <div class="hot-article-img">
31.<a href="/article/214954.html" target="_blank" title="10 年前改變世界的,可不止有 iPhone | 發車">
32.<!--視頻和圖片保留一個-->
33.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE2LzE2MjA0OTA5NjAxNS5qcGc?x-oss-process=image/format,png)
34.</a>
35.</div>, <div class="hot-article-img">
36.<a href="/article/214908.html" target="_blank" title="感謝微博替我作主">
37.<!--視頻和圖片保留一個-->
38.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE2LzAxMDQxMDkxMzE5Mi5qcGc?x-oss-process=image/format,png)
39.</a>
40.</div>, <div class="hot-article-img">
41.<a href="/article/215001.html" target="_blank" title="蘋果確認取消打賞抽成,但還有多少內容讓你以爲值得掏腰包?">
42.<!--視頻和圖片保留一個-->
43.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE3LzE1NDE0NzEwNTIxNy5qcGc?x-oss-process=image/format,png)
44.</a>
45.</div>, <div class="hot-article-img">
46.<a href="/article/214969.html" target="_blank" title="中國音樂的「全面付費」時代即將到來?">
47.<!--視頻和圖片保留一個-->
48.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE3LzEwMTIxODMxNzk1My5qcGc?x-oss-process=image/format,png)
49.</a>
50.</div>, <div class="hot-article-img">
51.<a href="/article/214964.html" target="_blank" title="百麗退市啓示錄:「一代鞋王」如何與新生代消費者漸行漸遠">
52.<!--視頻和圖片保留一個-->
53.![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWcuaHV4aXVjZG4uY29tL2FydGljbGUvY292ZXIvMjAxNzA5LzE2LzIxMzQwMDE2MjgxOC5qcGc?x-oss-process=image/format,png)
54.</a>
55.</div>]
這裏數據是抓取到了,可是太亂了,而且還有不少不是咱們想要的,下面就經過遍從來提煉出咱們的有效信息

3 提取有效信息

1.#遍歷列表,獲取有效信息
2.for news in allList:
3. aaa = news.select(‘a’)
4. # 只選擇長度大於0的結果
5. if len(aaa) > 0:
6. # 文章連接
7. try:#若是拋出異常就表明爲空
8. href = url + aaa[0][‘href’]
9. except Exception:
10. href=’’
11. # 文章圖片url
12. try:
13. imgUrl = aaa[0].select(‘img’)[0][‘src’]
14. except Exception:
15. imgUrl=""
16. # 新聞標題
17. try:
18. title = aaa[0][‘title’]
19. except Exception:
20. title = 「標題爲空」
21. print(「標題」,title,"\nurl:",href,"\n圖片地址:",imgUrl)
22. 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接口
最後給你你們分享一些小福利吧
連接:https://pan.baidu.com/s/1sMxwTn7P2lhvzvWRwBjFrQ

提取碼:kt2v

連接容易被舉報過時,若是失效了就加企鵝羣654234959 領取吧
相關文章
相關標籤/搜索