#【概要】
あるタグの中でストック数Top10の記事を抽出します。
#【環境】
windows8.1
python3.5
#【プログラム】
Pythonタグのランク付けを行いました。
実行方法 → python stock_rank.py > output.html
stock_rank.py
# -*- coding: utf-8 -*-
import urllib.request
from bs4 import BeautifulSoup
# Contribution数の初期化
cont = []
for i in range(10):
cont.append(0)
# タイトルの初期化
title = []
for i in range(10):
title.append("")
page_num = 1
while True:
try:
html = urllib.request.urlopen("https://qiita.com/tags/Python/items?page=" + str(page_num)).read()
soup = BeautifulSoup(html, "html.parser")
# クラスを指定してhtml抽出
title_all = soup.find_all(class_="publicItem_body")
# publicItem_bodyクラスがないページはとばす
if len(title_all) == 0:
continue
for i in range(20):
try:
# クラスを指定してhtml抽出
cont_all = soup.find_all(class_="publicItem_stockCount")
# 邪魔なタグを削除
cont_sakujo = str(cont_all[i]).replace('<i class="fa fa-stock "></i>','')
# cont_all_afterはstr型のためstringプロパティは使えない
# そのためBeautifulSoup型へ変換
cont_kazu = int(BeautifulSoup(cont_sakujo, "html.parser").string)
for j in range(10):
if cont_kazu >= cont[j]:
# Contribution数代入
cont.insert(j, cont_kazu)
cont.pop()
# タイトル代入
title.insert(j, title_all[i])
title.pop()
break
# 誰にもストックされていない記事はとばす
except:
continue
page_num += 1
# HTTP Error 404
except:
break
for i in range(len(title)):
print (str(cont[i]) + " " + str(title[i].a).replace('href="', 'href="http://qiita.com') + "<br>")
#【結果】
エンコードをutf-8で表示すると文字化けが発生したので、shift-jisにしました。
#【問題点】
プログラム実行時間が長い(>_<)
#【参考サイト】
Python3 + urllib + BeautifulSoupでネット上の情報を取得する
PythonとBeautiful Soupでスクレイピング
Beautiful Soupを使ってスクレイピング