第一次開始寫python進行爬蟲,如有不對請多諒解並提出

1、目的

  • 首先需要了解自己使用python的目的在於什麼
  • 我這裏使用python進行爬蟲,主要爬取網站的數據用
  • 這裏我用圖片之家的例子來給大家展示,請勿用於商用,概不負責。
  • 我們在爬取數據時候需要了解對方網站的特性,例如統一性和差異性。

2、案例分析

  • 例如這個網站 圖片之家的美女圖片
  • 當前頁碼的 清純少女 數據就是我們要爬取的數據以及裏面的詳情圖片
2.1、頁面分析

3、引入庫

  • 首先大家需要搭建 python 環境以及下載相關的編譯器,這裏我就不多講,大家百度查查。
  • 這裏我們要用到多個庫,同樣的 python 也有和 php 類似的庫,也需要引入。
  • 這裏我們就要用到 PYPI (類似 compoer

1、引入我們數據庫需要用到的 pymysql.cursors

pip install PyMySQL

2、引入協程,因爲跑得數據比較多,除了多開窗口跑之外我覺得最好還是用這個,但我這裏也不完全喫透

pip install greenlet

3、引入BeautifulSoup,主要用於取到頁面的標籤以及標籤內的標籤等,
這裏還可以引用xPath,點擊查看這兩者的 差異性

pip install beautifulsoup4

另外有些庫是python環境自帶的,例如requests /re/io/sys等,可以自行查找是否自帶。

4、數據庫設計

5、上代碼

#coding=utf8
# 導入需要使用到的數據模塊
import pymysql.cursors
# 協程
import greenlet
# 請求庫
import requests
# 解析庫
from bs4 import BeautifulSoup
import re
import io
import sys

# Connect to the database
connection = pymysql.connect(host='127.0.0.1',
                             user='user',
                             password='password',
                             database='database',
                             cursorclass=pymysql.cursors.DictCursor)

def f(everyUrl,imgType):
    r2= requests.get(everyUrl)
    r2.encoding=None
    result = r2.text
    soup = BeautifulSoup(result,'html.parser')
    result = soup.find('ul',class_='list_con_box_ul')
    if result is not None:
        result = result.find_all('li')
        if result is not None:
            print(1)
        else:
            for i in result:
                src = i.a.img.get('src') #圖片路徑
                title = i.a.img.get('alt') #標題
                href = i.a.get('href') #訪問路徑
                date = re.findall(r"\d+",str(href))[0] #日期
                url = "https://www.tupianzj.com" + href

                if title == None: break

                #搜索是否爬取過該網站
                sql = "SELECT * FROM b_beauty_atlas WHERE href = '" + url + "'"
                cursor.execute(sql)
                results = cursor.fetchone()
                #如果找到則跳出循環
                if results: break

                #獲取頁碼
                tp= requests.get(url)
                tp.encoding=None
                result2 = tp.text
                soup = BeautifulSoup(result2,'html.parser')
                page = soup.find('div',class_='pages')

                #判斷裏面是否存在照片詳情,不存在則跳過
                if page is None: break
                if page.find('li') is None: break
                if page.find('a') is None: break
                page = page.li.a
                page = re.findall(r"\d+",str(page))[0] #頁碼

                #匹配到對應的路徑
                href2 = re.sub('.html','',str(href))
                arr = []
                j = 1
                while j <= int(page):
                    if j==1:
                        tp= requests.get("https://www.tupianzj.com" + href2 + '.html' )
                    else:
                        tp= requests.get("https://www.tupianzj.com" + href2 + '_' + str(j) + '.html' )
                    tp.encoding=None
                    result3 = tp.text
                    soup = BeautifulSoup(result3,'html.parser')

                    bigpic = soup.find('div',id='bigpic')
                    if bigpic is None:break
                    if bigpic.find('a') is None:break
                    bigpic = bigpic.a.img.get('src')
                    arr.append(bigpic)
                    j += 1

                str2 = ','.join(arr)
                #數據庫操作
                sql = "INSERT INTO b_beauty_atlas (type,cover_img,href,images,send_time,title) VALUES (%s,%s,%s,%s,%s,%s)"
                val = (imgType, src, url, str2 , date, title)
                r = cursor.execute(sql,val)
                results = cursor.fetchone()

with connection:
    with connection.cursor() as cursor:

        # Read a single record
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

        # 0 xiezhen 清純美女 list_179_
        # 1 xinggan 性感美女 list_176_
        # 2 guzhuang 古裝美女 list_177_
        # 3 yishu 人體藝術 list_178_
        # 4 siwa 絲襪美女 list_193_
        # 5 chemo 香車美人 list_194_

        imgType = 3 # 類別ID
        ahead = 'yishu' # 類別
        ahead2 = 'list_178_' # 分頁編碼
        everyPage = 1# 第幾頁開始爬取數據 >=1
        pageinfo = 0 # 爬取頁數,如果是0表示爬全部

        if pageinfo == 0:
            # 獲取總共頁碼
            r= requests.get("https://www.tupianzj.com/meinv/" + ahead + '/')
            r.encoding=None
            result = r.text
            soup = BeautifulSoup(result,'html.parser')
            pageinfo = soup.find('span',class_='pageinfo').strong
            pageinfo = re.findall(r"\d+",str(pageinfo))[0] #頁碼

        while everyPage <= int(pageinfo):
            if everyPage == 1:
                everyUrl = "https://www.tupianzj.com/meinv/" + ahead + '/'
            else:
                everyUrl = "https://www.tupianzj.com/meinv/" + ahead + '/' + ahead2 + str(everyPage) + '.html'
            g1 = greenlet.greenlet(f)
            g1.switch(everyUrl,imgType)
            everyPage += 1
            connection.commit()
    print('成功!')
    cursor.close()

1、這裏需要注意數據庫存儲的時候要有 connection.commit()才能存儲成功!
2、爬取數據時候經常會出現沒有方法的保存,不要慌,根據提示去找到對應行代碼,大多都是因爲對方網站的差異性導致的,我們只要print()一下就能找到對應的問題,大多是找不到,我這裏都有判斷,如果沒找到直接跳出循環。

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