LoginSignup
1
0

はじめに

普段、Pythonでコードを書いていますが、最近Rubyにも興味を持ち始めました。
言語によって同じコードでどのくらい違いがあるのか気になったので、RubyとPythonでSeleniumを使った同じスクレイピングを行ってみました。
学習のためのアウトプットなので、間違い等あれば指摘していただけると幸いです。

Rubyのスクレイピング

1. パッケージのセットアップ

gem install selenium-webdriver

2. コード

require 'selenium-webdriver'

options = Selenium::WebDriver::Chrome::Options.new
options.add_argument('--headless')
driver = Selenium::WebDriver.for(:chrome, options: options)

driver.navigate.to 'https://qiita.com'

puts driver.title

elements = driver.find_elements(tag_name: 'a')
elements.each do |element|
  puts element.attribute('href')
end

driver.quit

3. 実行

ruby main.rb
出力
>> Qiita
>> https://qiita.com/
>> ....

Pythonのスクレイピング

1. パッケージのセットアップ

pip install selenium

2. コード

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)

driver.get("https://qiita.com")

print(driver.title)

elements = driver.find_elements(By.TAG_NAME, "a")
for element in elements:
    print(element.get_attribute("href"))

driver.quit()

3. 実行

python main.py
出力
>> Qiita
>> https://qiita.com/
>> ....

コードの比較

スクリーンショット

まとめ

PythonとRubyで同じスクレイピングを行ってみました。
コードの書き方には違いがありますが、基本的な部分は似ていると感じました。
RubyはPythonよりもコードが短くなることが多い印象ですが、どちらも使いやすい言語だと感じました。
個人的にはPythonの方が書きやすいと感じましたが、Rubyも使いこなせるようになりたいです。

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