0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

connpass APIアクセス時の403 Forbidden対処法:ユーザーエージェントの活用

Posted at

はじめに

APIリファレンス - connpassを読んで実施してみたが403エラーになってしまったので、備忘録かねてまとめます。

問題

最初、こんな感じでシンプルなプログラムを書いたら403が返ってきました。

実行したプログラム

main.py
import requests

def get_data():
    url = "https://connpass.com/api/v1/event/?keyword=python"
    response = requests.get(url)
    print("Status code:", response.status_code)
    print("Response body:", response.text)

if __name__ == "__main__":
    get_data()
実行した結果
Status code: 403
Response body: <html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
</body>
</html>

解決方法

以下のようにユーザーエージェントを含めることで値をちゃんと取得できるようになりました。

修正後のプログラム

main.py
import requests

def get_data():
    url = "https://connpass.com/api/v1/event/?keyword=python"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
    }
    response = requests.get(url, headers=headers)
    data = response.json()
    return data

if __name__ == "__main__":
    data = get_data()
    print(data)
実行した結果
{'results_start': 1, 'results_returned': 10, 'results_available': 10000, 'events': [{'event_id': 304019, 'title': '新ローレイヤー勉強会#1', 'catch': 'セキュリティ専門企業によるローレイヤー勉強会!', 'description': '<h1>申し込み・視聴方法</h1>\n<ul>\n<li>connpass画面「このイベントに申し込む」よりご登録ください</li>\n<li>当イベントは、Zoom にて開催予定です</li>\n<li>開催当日の朝、メールにて視聴URLをお送りしますので必ずご確認ください\n\u3000(※connpassページの「参加者への情報」にも記載します)</li>\n</ul>\n<h1>イベント概要</h1>・・・

おわりに

サイトには

※過度な検索やクローリングに対しては、アクセス制限を施す可能性があります。robots.txt を遵守してください。

というのがありますが、それ以外でもアクセス制限がほどこされてるのかと良い勉強になりました。

参考

※記事の構成についてはこちらの記事を参考にさせていただきました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?