【Python】メルカリの自動値下げツールを作成したので解説!

当ページのリンクには広告が含まれています。
メルカリの自動値下げツール
いずみ

こんな悩みを解決できる記事を書きました!

僕は現役フリーランスエンジニア(歴年)で、資格は個保有しています。

メルカリの自動値下げツールの作成方法を知りたい」とお悩みではありませんか?

メルカリの自動値下げツールはSeleniumを使えば簡単に作成できます。

いずみ

意外と簡単なのでサクッと解説します。

ということで、本記事ではメルカリの自動値下げツールの作成方法を解説します。

いずみ

すぐ読み終わるので、ぜひ最後まで読んでくださいませ。

執筆者/監修者
  • フリーランスエンジニア(保有資格個)
  • ブログ・アフィリエイト歴7年(2018年〜)
  • ブランドせどりで月利50万円⇨脱サラ
  • 投資(仮想通貨・FX)歴7年(2018年〜)
  • X(旧Twitter)フォロワー約1,900人
  • 運営者情報はこちら
いずみです
目次

【Python】メルカリの自動値下げツールの作成方法

早速ですが、Pythonでメルカリの自動値下げツールの作成方法を解説します。

共通処理

import logging
import platform
import pyperclip
import random
import time
from functools import wraps
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

options = Options()
options.add_argument("--user-data-dir=/Users/izumikohei/Library/Application Support/Google/Chrome/UserData")
driver = webdriver.Chrome(options=options)
driver.implicitly_wait(10)

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    datefmt="%Y/%m/%d %H:%M:%S"
)
logger = logging.getLogger(__name__)

def sleep(min=2, max=5):
    time.sleep(random.uniform(min, max))

def sleep_after_execution(min=2, max=5):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            sleep(min, max)
            return result
        return wrapper
    return decorator

@sleep_after_execution()
def open_site():
    driver.get("https://jp.mercari.com/mypage/listings")

def get_hrefs():
    hrefs = []

    hrefs_elem = driver.find_elements(By.CSS_SELECTOR, "#currentListing > div > div > div > a")
    for elem in hrefs_elem:
        href = elem.get_attribute("href")
        hrefs.append(href)
    
    return hrefs

@sleep_after_execution(30, 50)
def open_item_page(href):
    driver.get(href)

@sleep_after_execution(5, 10)
def click_checkout_button():
    driver.find_element(By.XPATH, "//div[@data-testid='checkout-button']/a").click()

@sleep_after_execution()
def scroll_to_price():
    price_input = driver.find_element(By.XPATH, "//input[@name='price']")
    driver.execute_script("arguments[0].scrollIntoView();", price_input)

@sleep_after_execution()
def set_reduce_price():
    price_input = driver.find_element(By.XPATH, "//input[@name='price']")
    price = int(price_input.get_attribute("value"))

    price_input.send_keys(Keys.COMMAND if platform.system() == "Darwin" else Keys.CONTROL, "a")
    sleep()

    price_input.send_keys(Keys.DELETE)
    sleep()

    reduce_price = price - 100
    price_input.send_keys(reduce_price)

@sleep_after_execution()
def scroll_to_bottom():
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

@sleep_after_execution()
def click_edit_button():
    driver.find_element(By.XPATH, "//button[@data-testid='edit-button']").click()

なるべく人間の操作に近づけるためにスリープ処理を入れています。

自動値下げ処理

import mercari_common as common
import tkinter as tk

driver = common.driver
logger = common.logger

def main():
    try:
        logger.info("処理開始")

        common.open_site()
        hrefs = common.get_hrefs()

        for count, href in enumerate(hrefs, start=1):
            logger.info(f"{len(hrefs)}件中{count}件目の値下げ中...")

            common.open_item_page(href)
            common.click_checkout_button()

            common.scroll_to_price()
            common.set_reduce_price()
            common.scroll_to_bottom()
            common.click_edit_button()

        logger.info("処理終了")
    except Exception as e:
        logger.error(f"予期せぬエラーが発生しました: {e}")
    finally:
        driver.quit()

if __name__ == "__main__":
    main()
    root = tk.Tk()
    root.geometry('1200x1200')
    root.title('メルカリ自動値下げツール')

    button = tk.Button(root, text="実行", command=main)
    button.grid(row=3, columnspan=2, pady=10)

    root.mainloop()

各商品を順番に値下げします。

いずみ

結構簡単にできた。

まとめ

今回は、メルカリの自動値下げツールの作成方法について解説しました。

以下が本記事のまとめになります。

まとめ
  • メルカリの自動値下げツールはSeleniumを使えば簡単。
  • なるべく人間の操作に近づけるのが大切(垢BANされるかもよ)
まとめ
  • おすすめ本
¥2,970 (2023/07/25 22:48時点 | Amazon調べ)

Pythonの勉強なら「」が体系的に学べるのでおすすめですよ♪

いずみ

最後までお読みいただき、ありがとうございました!

  • クソおすすめ本
¥4,480 (2024/06/01 23:28時点 | Amazon調べ)
いずみ

海外のエンジニアがどういった思考で働いているかが理解できます。

海外に行く気はないけど海外エンジニアの動向が気になる雑魚エンジニアにおすすめです(本当におすすめな本しか紹介しないのでご安心を)。

  • 他サイトも見てね
メルカリの自動値下げツール

この記事が気に入ったら
フォローしてね!

シェアしてね!
  • URLをコピーしました!
目次