第一次開始寫python進(jìn)行爬蟲,如有不對請多諒解并提出

1、目的

  • 首先需要了解自己使用python的目的在于什么
  • 我這里使用python進(jìn)行爬蟲,主要爬取網(wǎng)站的數(shù)據(jù)用
  • 這里我用圖片之家的例子來給大家展示,請勿用于商用,概不負(fù)責(zé)。
  • 我們在爬取數(shù)據(jù)時候需要了解對方網(wǎng)站的特性,例如統(tǒng)一性和差異性。

2、案例分析

  • 例如這個網(wǎng)站 圖片之家的美女圖片
  • 當(dāng)前頁碼的 清純少女 數(shù)據(jù)就是我們要爬取的數(shù)據(jù)以及里面的詳情圖片
2.1、頁面分析

3、引入庫

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

1、引入我們數(shù)據(jù)庫需要用到的 pymysql.cursors

pip install PyMySQL

2、引入?yún)f(xié)程,因為跑得數(shù)據(jù)比較多,除了多開窗口跑之外我覺得最好還是用這個,但我這里也不完全吃透

pip install greenlet

3、引入BeautifulSoup,主要用于取到頁面的標(biāo)簽以及標(biāo)簽內(nèi)的標(biāo)簽等,
這里還可以引用xPath,點擊查看這兩者的 差異性

pip install beautifulsoup4

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

4、數(shù)據(jù)庫設(shè)計

image.png

5、上代碼

#coding=utf8
# 導(dǎo)入需要使用到的數(shù)據(jù)模塊
import pymysql.cursors
# 協(xié)程
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') #標(biāo)題
                href = i.a.get('href') #訪問路徑
                date = re.findall(r"\d+",str(href))[0] #日期
                url = "https://www.tupianzj.com" + href

                if title == None: break

                #搜索是否爬取過該網(wǎng)站
                sql = "SELECT * FROM b_beauty_atlas WHERE href = '" + url + "'"
                cursor.execute(sql)
                results = cursor.fetchone()
                #如果找到則跳出循環(huán)
                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] #頁碼

                #匹配到對應(yīng)的路徑
                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)
                #數(shù)據(jù)庫操作
                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 人體藝術(shù) list_178_
        # 4 siwa 絲襪美女 list_193_
        # 5 chemo 香車美人 list_194_

        imgType = 3 # 類別ID
        ahead = 'yishu' # 類別
        ahead2 = 'list_178_' # 分頁編碼
        everyPage = 1# 第幾頁開始爬取數(shù)據(jù) >=1
        pageinfo = 0 # 爬取頁數(shù),如果是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、這里需要注意數(shù)據(jù)庫存儲的時候要有 connection.commit()才能存儲成功!
2、爬取數(shù)據(jù)時候經(jīng)常會出現(xiàn)沒有方法的保存,不要慌,根據(jù)提示去找到對應(yīng)行代碼,大多都是因為對方網(wǎng)站的差異性導(dǎo)致的,我們只要print()一下就能找到對應(yīng)的問題,大多是找不到,我這里都有判斷,如果沒找到直接跳出循環(huán)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容