欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實戰(zhàn)項目scrapy管道學習爬取在行高手數(shù)據(jù)

 更新時間:2021年11月13日 17:20:59   作者:夢想橡皮擦  
這篇文章主要為介紹了python實戰(zhàn)項目scrapy管道學習拿在行練手爬蟲項目,爬取在行高手數(shù)據(jù),本篇博客的重點為scrapy管道pipelines的應(yīng)用,學習時請重點關(guān)注

爬取目標站點分析

本次采集的目標站點為:https://www.zaih.com/falcon/mentors,目標數(shù)據(jù)為在行高手數(shù)據(jù)。

從前有一個網(wǎng)站叫在行,今天拿它練Python爬蟲

本次數(shù)據(jù)保存到 MySQL 數(shù)據(jù)庫中,基于目標數(shù)據(jù),設(shè)計表結(jié)構(gòu)如下所示。

從前有一個網(wǎng)站叫在行,今天拿它練Python爬蟲

對比表結(jié)構(gòu),可以直接將 scrapy 中的 items.py 文件編寫完畢。

class ZaihangItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()  # 姓名
    city = scrapy.Field()  # 城市
    industry = scrapy.Field()  # 行業(yè)
    price = scrapy.Field()  # 價格
    chat_nums = scrapy.Field()  # 聊天人數(shù)
    score = scrapy.Field()  # 評分

編碼時間

項目的創(chuàng)建過程參考上一案例即可,本文直接從采集文件開發(fā)進行編寫,該文件為 zh.py。
本次目標數(shù)據(jù)分頁地址需要手動拼接,所以提前聲明一個實例變量(字段),該字段為 page,每次響應(yīng)之后,判斷數(shù)據(jù)是否為空,如果不為空,則執(zhí)行 +1 操作。

請求地址模板如下:

https://www.zaih.com/falcon/mentors?first_tag_id=479&first_tag_name=心理&page={}

當頁碼超過最大頁數(shù)時,返回如下頁面狀態(tài),所以數(shù)據(jù)為空狀態(tài),只需要判斷 是否存在 class=emptysection 即可。

從前有一個網(wǎng)站叫在行,今天拿它練Python爬蟲

解析數(shù)據(jù)與數(shù)據(jù)清晰直接參考下述代碼即可。

import scrapy
from zaihang_spider.items import ZaihangItem
class ZhSpider(scrapy.Spider):
    name = 'zh'
    allowed_domains = ['www.zaih.com']
    page = 1  # 起始頁碼
    url_format = 'https://www.zaih.com/falcon/mentors?first_tag_id=479&first_tag_name=%E5%BF%83%E7%90%86&page={}'  # 模板
    start_urls = [url_format.format(page)]
    def parse(self, response):
        empty = response.css("section.empty") # 判斷數(shù)據(jù)是否為空
        if len(empty) > 0:
            return # 存在空標簽,直接返回
        mentors = response.css(".mentor-board a") # 所有高手的超鏈接
        for m in mentors:
            item = ZaihangItem() # 實例化一個對象
            name = m.css(".mentor-card__name::text").extract_first()
            city = m.css(".mentor-card__location::text").extract_first()
            industry = m.css(".mentor-card__title::text").extract_first()
            price = self.replace_space(m.css(".mentor-card__price::text").extract_first())
            chat_nums = self.replace_space(m.css(".mentor-card__number::text").extract()[0])
            score = self.replace_space(m.css(".mentor-card__number::text").extract()[1])
            # 格式化數(shù)據(jù)
            item["name"] = name
            item["city"] = city
            item["industry"] = industry
            item["price"] = price
            item["chat_nums"] = chat_nums
            item["score"] = score
            yield item
        # 再次生成一個請求
        self.page += 1
        next_url = format(self.url_format.format(self.page))
        yield scrapy.Request(url=next_url, callback=self.parse)
    def replace_space(self, in_str):
        in_str = in_str.replace("\n", "").replace("\r", "").replace("¥", "")
        return in_str.strip()

開啟 settings.py 文件中的 ITEM_PIPELINES,注意類名有修改

ITEM_PIPELINES = {
   'zaihang_spider.pipelines.ZaihangMySQLPipeline': 300,
}

修改 pipelines.py 文件,使其能將數(shù)據(jù)保存到 MySQL 數(shù)據(jù)庫中
在下述代碼中,首先需要了解類方法 from_crawler,該方法是 __init__ 的一個代理,如果其存在,類被初始化時會被調(diào)用,并得到全局的 crawler,然后通過 crawler 就可以獲取 settings.py 中的各個配置項。

除此之外,還存在一個 from_settings 方法,一般在官方插件中也有應(yīng)用,示例如下所示。

@classmethod
def from_settings(cls, settings):
    host= settings.get('HOST')
    return cls(host)

@classmethod
def from_crawler(cls, crawler):
  # FIXME: for now, stats are only supported from this constructor
  return cls.from_settings(crawler.settings)

在編寫下述代碼前,需要提前在 settings.py 中寫好配置項。

settings.py 文件代碼

HOST = "127.0.0.1"
PORT = 3306
USER = "root"
PASSWORD = "123456"
DB = "zaihang"

pipelines.py 文件代碼

import pymysql
class ZaihangMySQLPipeline:
    def __init__(self, host, port, user, password, db):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.db = db
        self.conn = None
        self.cursor = None
    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            host=crawler.settings.get('HOST'),
            port=crawler.settings.get('PORT'),
            user=crawler.settings.get('USER'),
            password=crawler.settings.get('PASSWORD'),
            db=crawler.settings.get('DB')
        )
    def open_spider(self, spider):
        self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, db=self.db)
    def process_item(self, item, spider):
        # print(item)
        # 存儲到 MySQL
        name = item["name"]
        city = item["city"]
        industry = item["industry"]
        price = item["price"]
        chat_nums = item["chat_nums"]
        score = item["score"]
        sql = "insert into users(name,city,industry,price,chat_nums,score) values ('%s','%s','%s',%.1f,%d,%.1f)" % (
            name, city, industry, float(price), int(chat_nums), float(score))
        print(sql)
        self.cursor = self.conn.cursor()  # 設(shè)置游標
        try:
            self.cursor.execute(sql)  # 執(zhí)行 sql
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        return item
    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()

管道文件中三個重要函數(shù),分別是 open_spider,process_item,close_spider

# 爬蟲開啟時執(zhí)行,只執(zhí)行一次
def open_spider(self, spider):
    # spider.name = "橡皮擦"  # spider對象動態(tài)添加實例變量,可以在spider模塊中獲取該變量值,比如在 parse(self, response) 函數(shù)中通過self 獲取屬性
    # 一些初始化動作
    pass

# 處理提取的數(shù)據(jù),數(shù)據(jù)保存代碼編寫位置
def process_item(self, item, spider):
    pass

# 爬蟲關(guān)閉時執(zhí)行,只執(zhí)行一次,如果爬蟲運行過程中發(fā)生異常崩潰,close_spider 不會執(zhí)行
def close_spider(self, spider):
    # 關(guān)閉數(shù)據(jù)庫,釋放資源
    pass

爬取結(jié)果展示

從前有一個網(wǎng)站叫在行,今天拿它練Python爬蟲

以上就是python實戰(zhàn)項目scrapy管道學習爬取在行高手數(shù)據(jù)的詳細內(nèi)容,更多關(guān)于python scrapy管道學習爬取在行的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 基于PyQt5制作一個windows通知管理器

    基于PyQt5制作一個windows通知管理器

    python框架win10toast可以用來做windows的消息通知功能,通過設(shè)定通知的間隔時間來實現(xiàn)一些事件通知的功能。本文將利用win10toast這一框架制作一個windows通知管理器,感興趣的可以參考一下
    2022-02-02
  • 對PyTorch中inplace字段的全面理解

    對PyTorch中inplace字段的全面理解

    這篇文章主要介紹了對PyTorch中inplace字段的全面理解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • python的正則表達式和re模塊詳解

    python的正則表達式和re模塊詳解

    這篇文章主要為大家詳細介紹了python的正則表達式和re模塊,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-02-02
  • 詳解Python發(fā)送郵件實例

    詳解Python發(fā)送郵件實例

    這篇文章主要介紹了Python發(fā)送郵件實例,Python發(fā)送郵件需要smtplib和email兩個模塊,感興趣的小伙伴們可以參考一下
    2016-01-01
  • python爬蟲selenium和phantomJs使用方法解析

    python爬蟲selenium和phantomJs使用方法解析

    這篇文章主要介紹了python爬蟲selenium和phantomJs使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-08-08
  • django-初始配置(純手寫)詳解

    django-初始配置(純手寫)詳解

    這篇文章主要介紹了django-初始配置(純手寫)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07
  • 利用Python優(yōu)雅的登錄校園網(wǎng)

    利用Python優(yōu)雅的登錄校園網(wǎng)

    這篇文章主要介紹了如何利用Python優(yōu)雅的登錄校園網(wǎng),幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-10-10
  • 用Python編寫簡單的gRPC服務(wù)的詳細過程

    用Python編寫簡單的gRPC服務(wù)的詳細過程

    gRPC 是可以在任何環(huán)境中運行的現(xiàn)代開源高性能 RPC 框架。接下來通過本文給大家介紹用Python編寫簡單的gRPC服務(wù)的詳細過程,感興趣的朋友一起看看吧
    2021-07-07
  • Python類和實例的屬性機制原理詳解

    Python類和實例的屬性機制原理詳解

    這篇文章主要介紹了Python類和實例的屬性機制原理詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • python實現(xiàn)批量獲取指定文件夾下的所有文件的廠商信息

    python實現(xiàn)批量獲取指定文件夾下的所有文件的廠商信息

    這篇文章主要介紹了python實現(xiàn)批量獲取指定文件夾下的所有文件的廠商信息的方法,是非常實用的技巧,涉及到文件的讀寫與字典的操作等技巧,需要的朋友可以參考下
    2014-09-09

最新評論