0
0

More than 3 years have passed since last update.

【悪用厳禁】自分のQiita記事のview数を取得する

Last updated at Posted at 2020-06-17

前々回にグラフ系の取り組みをしてみたのですが、データ自体がちょっと微妙だったのでそのリベンジも兼ねてQiitaに投稿した記事のview数の遷移をグラフ化するといったことをしようと思います!

今日の目標/成果物

今日はQiitaに自分が投稿した記事のview数を取得するコードを書く

コードと資料

1. スクレイピングのベースコードを準備

Qiitaのスクレイピングについては↑の記事にて一回書いているので基本的にはこちらを流用します。

crawler.rb
require 'nokogiri'
require 'mechanize'
require 'selenium-webdriver'

def selemium_init
  ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
  # caps = Selenium::WebDriver::Remote::Capabilities.chrome('chromeOptions' => { args: ["--user-agent=#{ua}", 'window-size=1280x800', '--incognito'] }) # シークレットモード
  caps = Selenium::WebDriver::Remote::Capabilities.chrome('chromeOptions' => {args: ["--headless","--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu", "--user-agent=#{ua}", 'window-size=1280x800']})

  client = Selenium::WebDriver::Remote::Http::Default.new
  driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps  
end

driver = selemium_init
driver.navigate.to 'https://qiita.com/login'
driver.execute_script("document.getElementsByName('identity')[0].value = 'メールアドレス'")
driver.execute_script("document.getElementsByName('password')[0].value = 'パスワード'")
driver.execute_script("document.getElementsByName('commit')[0].click()")
sleep 1

こちらがログイン処理をするコードとなっています。

2. 自分のページの情報を取得

ここから、今回は自分のページの一覧を取得して、そこのページに飛んでview集を取得するので

crawler.rb
driver.navigate.to 'https://qiita.com/itaya'
sleep 1
doc = Nokogiri::HTML.parse(driver.page_source, nil, 'utf-8')
doc.css('.AllArticleList__Item-mhtjc8-2').each do |div|
  driver.navigate.to "https://qiita.com" + div.css('.AllArticleList__ItemBodyTitle-mhtjc8-6')[0]['href']
  sleep 1
  article_doc = Nokogiri::HTML.parse(driver.page_source, nil, 'utf-8')
  p article_doc.css('.it-Header_pv')[0].text.split(" ")[0]
end

こんな感じになります。

3. いざ実行!!

こちらを実行すると

"99"
"56"
"218"
"212"
"120"
"107"
"288"
"112"
"213"
"93"
"111"
"128"
"131"
"149"
"383"
"801"
"4629"
"510"
"1086"

このような感じに1ページ目に表示されている記事のview数が取得できます。
ただこれだけでは2ページ目以降の記事のview数が取得できないので、明日その部分作りたいと思います....

※あまりに多くのリクエストはサーバーに負荷がかかるので注意しましょう!!!

てか、これ普通にQiitaのAPI使えばいいじゃん...
https://qiita.com/api/v2/docs#%E6%8A%95%E7%A8%BF

メモ
毎日投稿14日目

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