1. 程式人生 > >【Python3爬蟲】爬取中國國家地理的62個《古鎮》和363張攝影照片

【Python3爬蟲】爬取中國國家地理的62個《古鎮》和363張攝影照片

宣告:爬蟲為學習使用,請各位同學務必不要對當放網站或i伺服器造成傷害。務必不要寫死迴圈。

-

思路:古鎮——古鎮列表(迴圈獲取古鎮詳情href)——xx古鎮詳情(獲取所有img的src)

-

from bs4 import BeautifulSoup
import urllib.request
import requests
import os
import re


# 儲存文章裡面的圖片
def down(url, num):

    # 獲取網頁
    response = urllib.request.urlopen(url)
    html = response.read().decode('utf-8')  # 編碼格式gb2312,utf-8,GBK
    html_string = str(html)  # 轉換成string,可以直接向資料庫新增

    soup = BeautifulSoup(html_string, "html.parser")  # 解析網頁標籤

    # 匹配抓取區域
    # 該div的class由img和aImg兩種,要判斷一下
    pid = soup.findAll('div', {"class": "img"})
    if len(pid) == 0:
        pid = soup.findAll('div', {"class": "aImg"})
        pass

    print(pid)

    pid2 = soup.find("article").find("h1")  # 本篇文章的標題
    # 清除html標籤
    pattern = re.compile(r'<[^>]+>', re.S)
    txt = pattern.sub('', str(pid2))
    print(txt)

    for img_html in pid:
        img_src = img_html.find('img')['src']

        root = "D:/python/do/spider/guojiadili/" + txt + "/"  # 沒有最後一級資料夾目錄則會自動建立
        img_name = img_src.split("/")[-1].replace('@!rw9', '').replace('@!rw14', '').replace('@!rw7', '').replace('@!rw8', '').replace('@!rw10', '').replace('@!rw11', '').replace('@!rw12', '').replace('@!rw13', '').replace('@!rw6', '').replace('@!rw5', '').replace('@!rw4', '').replace('@!rw3', '').replace('@!rw2', '').replace('@!rw1', '').replace('@!rw15', '').replace('@!rw16', '').replace('@!rw17', '').replace('@!rw18', '').replace('@!rw19', '')  # 去除圖片字尾後面的特殊字串,得到真實圖片名
        print(img_name)
        path = root + img_name  # 儲存檔案的名字

        # 儲存圖片到本地
        try:
            if not os.path.exists(root):
                os.mkdir(root)
            if not os.path.exists(path):
                r = requests.get(img_src)
                r.raise_for_status()
                # 使用with語句可以不用自己手動關閉已經開啟的檔案流
                with open(path, "wb") as f:  # 開始寫檔案,wb代表寫二進位制檔案
                    f.write(r.content)

                num += 1
                print("儲存檔案成功=" + str(num))
            else:
                print("檔案已存在")
        except Exception as e:
            print("檔案儲存失敗:" + str(e))

        pass

    pass


# down("http://www.dili360.com//article/p549a356731fc659.htm", 0)


# 解析文章目錄中所有的文章地址
def list(url, number):
    # 獲取網頁
    response = urllib.request.urlopen(url)
    html = response.read().decode('utf-8')  # 編碼格式gb2312,utf-8,GBK
    html_string = str(html)  # 轉換成string,可以直接向資料庫新增

    soup = BeautifulSoup(html_string, "html.parser")  # 解析網頁標籤

    # 匹配抓取區域
    # pid = soup.find(attrs={"id": "content"})
    pid = soup.findAll('div', {"class": "thumb-img"})
    print(pid)

    print("第" + str(number) + "頁")

    for a_html in pid:
        a_href = a_html.find('a')['href']
        print(a_href)

        new_url = "http://www.dili360.com" + a_href  # 文章地址
        print(new_url)
        print(type(new_url))

        down(new_url, 0)  # 獲取單個列表中單個文章的圖片

        pass
    pass


# list('http://www.dili360.com/Travel/sight/20194/1.htm')


# 解析有多少個文章目錄
page = 1  # 起始目錄標號
while page <= 14:  # 最大目錄標號
    list('http://www.dili360.com/Travel/sight/20247/' + str(page) + '.htm', 1)  # 單個目錄地址
    page += 1
    pass
else:
    print("所有文章儲存完畢!")

-

提示,迴圈sight/xxxxx.htm可以把整個分類全部爬下來。但是不建議你這樣學習。

-

旅遊就去這些古鎮吧!

-