何か情報を集める際、自分でサイトを検索し、一つ一つの記事を追っていくのは面倒です。
そこで、Webスクレイピングというものがあると知ったので、
早速試してみます。
Webスクレイピングとは
Webスクレイピング:WebサイトからHTMLデータを収集し、特定のデータを抽出すること。
scraping:こする・削ること。
**注意事項**
Webスクレイピングの注意事項一覧
とりあえず、このブログのタイトルを取得するプログラム。
プログラム
# coding: UTF-8 from bs4 import BeautifulSoup import urllib3 # アクセスするURL url = "https://ml-begin.hatenablog.com" # URLにアクセスし、html取得 http = urllib3.PoolManager() html = http.request("GET",url) # htmlをBeautifulSoupで扱う soup = BeautifulSoup(html.data, "html.parser") # タイトル要素取得 title_tag = soup.title # 要素の文字列取得 title = title_tag.string # タイトルを出力 print(title)
結果
/anaconda3/lib/python3.6/site-packages/urllib3/connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) ml_begin’s blog←
結果行の最後のところにタイトル表示されてます。
その上のssl-warningについてはこちら。
http://73spica.tech/blog/requests-insecurerequestwarning-disable/
こんな感じで非表示に。SSL証明書についても調べてみます..
サーバーへのアクセス間隔を1秒以上空けるようにすれば良さそうなので、次回は定期的にアクセスした結果を出力したい。
参考:
Python Webスクレイピング 実践入門
Python初心者が、ISE ERS API を利用してスクリプトを書いてみた