LoginSignup
0
0

More than 3 years have passed since last update.

PythonでHTTPを操作する : requests

Last updated at Posted at 2019-06-01

はじめに

本記事では、requestsライブラリを使用してHTTPを処理します。

実装

example.py
import requests

url = 'http://www.webscrapingfordatascience.com/basichttp/'
r = requests.get(url)
print(r.text)
  • 最初にrequestsモジュールをインポートする。
  • 続いて、http://www.webscrapingfordatascience.com/basichttp/ のコンテンツの取得に取りかかる。このWebページにアクセスしてみると「Hello from the web!」という文字列がページに表示される。この文字列を、Pythonを使って抽出したい。
  • この例では、requests.getメソッドを使用して、urlに対する「HTTP GET」リクエストを実行している。
  • requests.getメソッドは、requests.ResponseというPythonオブジェクトを返す。このオブジェクトには、取得したHTTPレスポンスに関する多くの情報が格納されている。
  • r.textにはHTTPレスポンスのコンテンツ本体がテキスト形式で格納される。

結果

Hello from the web!

何も問題がなければ、以下の行が表示されます。

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