UdemyでPythonを勉強した結果を残すブログ。

40歳でプログラミング始めて転職までいけるのかを実録してみます。

スクレイピングをする時にAmazonとかでうまくできない場合の設定テンプレ

myhttpheader.com

 

アマゾンで普通にrequestで思ったエレメントがとれない場合は

上のhttpheader.comとかでuser-agentとaccept-languageのデータをとって

headerに追加してrequestsすると思い通りのものがとれる。

 

それでもできなかった場合はBS4のparserをhtml.parserからlxmlにする。

 

 

import requests
from bs4 import BeautifulSoup
URL = "https://www.amazon.com/Enhanced-Splashproof-Portable-Bluetooth-Radiator/dp/B010OYASRG/"
response = requests.get(url=URL, headers={"Accept-Language":"ja,en-US;q=0.9,en;q=0.8r",
'User-Agent':"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36"})
soup = BeautifulSoup(response.text, "lxml")

price = float(soup.select_one(".a-price span:nth-of-type(2)").getText().replace("$", ""))
print(price)

$を抜かした値段だけ出力されます。$もいるならreplaceを消す