第一次开始写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()一下就能找到对应的问题,大多是找不到,我这里都有判断,如果没找到直接跳出循环。

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