web-technical-blog

web開発に関する技術メモ

Twitterのタイムラインのスクレイピング

pip install twitterpastcrawler  # twitterページをクロールするライブラリ
pip install requests            # HTTPライブラリ
pip install beautifulsoup4      # スクレイピング処理に必要
pip install wordcloud           # タグクラウドを生成できるライブラリ
pip install pillow              # 画像処理ライブラリ
pip install matplotlib          # グラフ描画ライブラリ
pip install janome              # 内部で辞書を持っているので、Mecabをインストールする必要がない
  • 注意点
    • pipでインストールした「twitterpastcrawler」を修正が必要かもしれない
      • useragent_windows.datファイルのUA(ユーザーエージェント)は新しいものに書き換える必要あり
Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like Gecko)CLR 3.0.30729; Media Center PC 6.0)
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.3) Gecko/20100402 Prism/1.0b4.NET CLR 3.0.30729; Media Center PC 6.0; Zune 4.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E; Maxthon 2.0)2.0.50727; Media Center PC 6.0; Maxthon 2.0)
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2a2pre) Gecko/20090908 Ubuntu/9.04 (jaunty) Namoroka/3.6a2pre GTB5 (.NET CLR
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2a1) Gecko/20090806 Namoroka/3.6a1
Mozilla/5.0 (X11; U; NetBSD i386; en-US; rv:1.9.2.3) Gecko/20100403 Namoroka/3.6.3
Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.1) Gecko/20061204
Mozilla/5.0 (Macintosh; U; Intel Mac OS X; nl-NL; rv:1.8.1.3) Gecko/20080722
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-au; rv:1.9.0.1) Gecko/2008070206
  • 変更した場合でもエラーする可能性はある
  • crawler.py
    • 170行目付近
      • windows環境だとJSONのデコード処理でエラーするので
##with open(crawler.output_file, "at") as f:
with open(crawler.output_file, "at", encoding='utf-8') as f: ← 書き換える(utf-8)にする
  • 234行目付近
    • csvファイルを書き出し後に継続して処理したい場合はsys.exit(1)だと処理が終了してしまうので、returnに変更する
if self.last_min_pos is not None:
    if not connection_cut and min_pos == self.last_min_pos:
        print("Starting to loop! Exitting with status:")
        self.dump()
        return
        ##sys.exit(1)
import csv
from janome.tokenizer import Tokenizer
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from collections import defaultdict
import twitterpastcrawler
import os

hash_tag = '#DMC体験版'
output_file = '#DMC体験版.csv'

# crawel
crawel = twitterpastcrawler.TwitterCrawler(
    query=hash_tag,
    output_file=output_file,
    max_depth=10
)
crawel.crawl()

# 名詞だけ抽出、単語をカウント
def counter(texts):
    t = Tokenizer()
    # = Tokenizer("user_simpledic.csv", udic_type="simpledic", udic_enc="utf8")
    #t = Tokenizer("userdic.csv",udic_enc="utf8")
    words_count = defaultdict(int)
    words = []
    for text in texts:
        tokens = t.tokenize(text)
        for token in tokens:
            # 品詞から名詞だけ抽出
            if token.part_of_speech.split(',')[0] == '名詞':
                words_count[token.base_form] += 1
                words.append(token.base_form)
    return words_count, words

with open(output_file,'r',encoding='utf_8') as f:
    reader = csv.DictReader(f, delimiter=',')
    texts = []
    for row in reader:
        texts.append(row['text'])

words_count, words = counter(texts)
text = ' '.join(words)

# wordcloudオブジェクトの生成
# font指定
if os.name == 'nt':
    font_path='C:\Windows\Fonts\HGRSGU.TTC'
else:
    font_path = '/System/Library/Fonts/ヒラギノ丸ゴ ProN W4.ttc'

# 画像に出したくない単語リスト(本当はもっと色々)
stop_words = ['なる', 'ある', 'いる', 'する', 'ない', 'れる', 'ため', 'こと', 'もの', 'さん', 'これ', 'ここ']

wordcloud = WordCloud(background_color="white",
                      font_path=font_path,
                      collocations = False, # 複合語のオプションをオフ
                      stopwords = set(stop_words),
                      width=900,
                      height=500).generate(text)

# 1文字を表示させたい場合
##wordcloud = WordCloud(background_color="white",font_path=font_path,regexp=r"\w+").generate(text)

# グラフ出力
##plt.figure(figsize=(15,12))
plt.imshow(wordcloud,interpolation='bilinear')
plt.imshow(wordcloud)
plt.axis("off")
plt.show()