LoginSignup
2
2

More than 1 year has passed since last update.

【Python】seleniumを使ってVPS上でスクレイピングする方法【selenium】

Last updated at Posted at 2021-09-23

概要

pythonを使ってVPS上でseleniumを使うときにハマったのでtipsをまとめる。

selenium のインストール

conda install selenium 

chrome, chromedriver のインストール

chromeのインストール

sudo apt-get install libappindicator1 fonts-liberation
sudo apt-get install xdg-utils libxss1
curl -O https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb

seleniumはchromedriverを使うので、ダウンロードしてきて、実行ファイルと同じディレクトリに配置する。

URL:ChromeDriver - WebDriver for Chrome
https://sites.google.com/a/chromium.org/chromedriver/downloads
↑上記の適するバージョンをダウンロードしてきて、同じディレクトリに配置。

selenium を使って、Yahoo! 天気から大阪の天気をとってくる


#ヘッドレスの設定をするため、Optionsクラスのインポートを行う
from selenium.webdriver.chrome.options import Options

#変数optionsに格納するためOptionsのインスタンスを生成する。
options = Options()

#headlessの設定をTrueにする
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

#webdriverを起動する
driver = webdriver.Chrome(options=options)

#URLを開く(下記はYahoo!天気)
driver.get("https://weather.yahoo.co.jp/weather/")

high = driver.find_elements_by_xpath('//*[@id="map"]/ul/li[8]/a/dl/dd/p[2]/em[1]')
low = driver.find_elements_by_xpath('//*[@id="map"]/ul/li[8]/a/dl/dd/p[2]/em[2]')

#大阪の最高気温
print(high[0].text)

#大阪の最低気温
print(low[0].text)

出力

'30'
'22'

参考にしたサイト

さくらの VPS 上の Ubuntu で Headless Chrome を動かす
https://loumo.jp/archives/17035

【EC2】seleniumのwebdriverを実行する方法
https://qiita.com/shizen-shin/items/7028c3095686292e8084

2
2
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
2
2