"クロスワード辞典"の検索結果をスクレイピング
Webサイト"クロスワード辞典"の検索結果のスクレイピングを行った。
クロスワード辞典
言語&ライブラリ : python , requests , BeautifulSoup
ソースコード
requestsを使用して、検索結果のhtmlを取得
import requests def search(search_word): """クロスワード辞典 検索の検索結果のhtmlを返す関数 Args: serch_word (str) :検索キーワード returns: html (str) :検索結果のhtml """ url = 'http://cross.matrix.jp/search.cgi' print(search_word) req = requests.post(url, {'key':search_word.encode('euc-jp')}) return req.text
取得したhtmlに対してBeautifulSoupでスクレイピング。
ここでは、検索結果を引数で返すようにした。
from bs4 import BeautifulSoup def get_search_result(html): """検索結果のヒット数を返す Args: html (str) :クロスワード辞典の検索結果ページのhtml returns: num (int) :ヒット件数 words_list :検索で出てきた単語 ['カタカナ',['漢字']] """ try: soup = BeautifulSoup(html, "html.parser") words_list=[] str = soup.find("div", class_="search-result") print(str) if str == None: return 0 ,words_list text = str.get_text() i = -1 for line in text.splitlines(): i+=1 if i == 0: continue data = line.split("\xa0") words=[] words.append(data[0]) words.append(data[2].split("、")) print(words) words_list.append(words) return i ,words_list except urllib.error.URLError as e: print(e) return 0
実行例
■検索語 ねこ ■検索結果 <div class="search-result"> ネコ : 猫 <a class="edit" href="entry.cgi?rm=edit&keyword=%A5%CD%A5%B3&search=%A4%CD%A4%B3">(編集)</a><br/> </div> ■返り値 ['ネコ', ['猫']]