3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

メルカリの検索結果からタイトルと値段をスクレイピングしたかった

Last updated at Posted at 2021-10-16

前回までのあらすじ

前回の記事では、とりあえずアクセスしてページ内容を表示するものだった。
せっかくなので、取れそうな情報を抜き出してみた。

取りたい情報

  • 検索結果として表示されたページの商品名
  • 上記商品名に対応する値段

取得手順

  1. スタートページにヘッドレスモードでアクセス
  2. ちょっと待ってからページ内にある商品名と値段を取得、画面出力
  3. 「次へ」ボタンを探してクリック、同様に取得/出力しながらループ。
  4. クリックできなければループを抜けて終了

ソースコード

mercari.py
# メルカリ上で動的レンダリングされた商品情報を取得し、すべてのページから商品名、価格、タイトルを取得する。
from selenium import webdriver
from time import sleep
from selenium.common.exceptions import *

options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument("--window-size=1920,1080")
options.add_argument("--disable-gpu")    
options.add_argument(
    "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
browser = webdriver.Chrome('chromedriver.exe',options=options)

# mercari:指定条件を検索したURLにアクセス
url = 'https://jp.mercari.com/search?status=on_sale&page=1&t1_category_id=5&category_id=5'

browser.get(url)
sleep(3)

# カウンタ(表示用)
no = 0
# 外ループ:メルカリの次へボタンが無くなるまで。
while True :

    sellItems = browser.find_elements_by_tag_name("mer-item-thumbnail")
    # 内ループ:ページ内のアイテム情報を取得しきるまで。
    for item in sellItems :
        no += 1
        name = item.get_attribute("item-name")
        price = item.get_attribute("price")
        print(str(no) + ' : ' + name + ' : \\' + price)
    
    # 「次へ」ボタンを探して、見つかればクリック
    try:
        # 自動でページ遷移すると画面読み込み時の初期処理に割り込まれてボタン押下が出来ないので、execute_scriptで対策する。
        buttonClick = browser.find_element_by_xpath("//mer-button[@data-testid='pagination-next-button']")
        browser.execute_script("arguments[0].click();",buttonClick)
        sleep(3)

    # 「次へ」ボタンが無ければループを抜ける
    except NoSuchElementException:
        break
# 終了処理(ヘッドレスブラウザを閉じる)
browser.quit()

実行結果

実行結果
No(数字) : 商品名 : \価格

もうちょっと発展させてCSVに出力したり、スタートページを別ファイル読み込みにしたりと、
やれることはまだありそう。
楽しくなってきたので気が向いたらまた更新します。よろしくね。

参考

【Python】Selenium:ElementClickInterceptedExceptionエラーの原因と解決方法
button.click()が単純にできなかったので、エラーメッセージに出てきたExceptionググったら
execute_script()を使う方法があったので使わせてもらいました。

3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?