1
0

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 5 years have passed since last update.

60日目 AmazonからASINと型番と各種コードをサクっと取ってこれるコードを考えてみました。

Posted at

最初は、tableやclassでスクレイピングできるかと思っていました。
しかしパターンが複数あり、振り分けの条件が複雑になりすぎる・・・悩んでいたところ、文字だけを抜き出して、行ごとにリストに入れてforで回す方法を見つけました。

試してみた所いい感じに動いてくれました。

Pythonのスクレイピングで文字だけを抜き出す汎用的な方法

Amazonどうやってデータを管理しているんだろう。
今回の件ですごく興味がわいてきました。
これだけ状態が複合していて、ある程度同じ体裁を保ちつつ何年も運用している。それでいてソースが読める。設計した人はすごいと思いました。

getASIN.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import chromedriver_binary
from selenium.webdriver.common.action_chains import ActionChains
from bs4 import BeautifulSoup

def getASIN(url):

  #ブラウザを立ち上げる
  options = Options()
  browser = webdriver.Chrome(options=options)  
  browser.get(url)

  #htmlを取得する
  html = browser.page_source
  
  #BeautifulSoupにほうりこむ
  soup = BeautifulSoup(html, features="html.parser")

 #scriptやstyleを含む要素を削除する
  for script in soup(["script", "style"]):
    script.decompose()

  #テキストのみを取得=タグは全部取る
  text=soup.get_text()
  
  #textを改行ごとにリストに入れて、前後の空白を削除する
  lines= [line.strip() for line in text.splitlines()]

  #リストの空白を削除する
  #text="\n".join(line for line in lines if line)
  #print(text)
 
 #検索キーワードを設定
  key1 = "ASIN"
  key2 = ["型番","JAN","メーカー型番","製造元リファレンス"]

  #noneで初期化する
  ASIN = "none"
  TYPE = "none"

 #リストを一行ずつ確認していく
  for line in lines:
    #"ASIN"が行に含まれていたら変数ASINに入れて、その行を表示する。
    if key1 in line: ASIN = line.strip(key1).strip(":").strip("").strip()

    #キーワードが行に含まれていたら変数TYPEに入れて、その行を表示する。
    for key in key2:
      if key in line: TYPE = line.strip(key).strip(":").strip("").strip()

 #結果を表示する
  print(TYPE,ASIN,sep=",")

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?