【Python】pip install requests でエラー pip3 install requests でインストール成功

とりあえず Mac に Python3 のインストールまでは完了

スクレイピングをやってみたいため、requests モジュールをインストールしたい。

環境

OS: macOS Catalina バージョン 10.15.4
Python: Python 3.8.3

「pip install requests」を入力してみる

なるほど、コマンドラインに「pip install requests」と入力すれば良いわけか。コマンドそのまま「requests をインストール」という事ね。

というわけでそのまま Python のシェルで「pip install requests」と入力して Enter。

 % python3
Python 3.8.3 (v3.8.3:6f8c8320e9, May 13 2020, 16:29:34) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> pip install requests

エラー「SyntaxError: invalid syntax」

すると下記の表示が。

>>> pip install requests
  File "<stdin>", line 1
    pip install requests
        ^
SyntaxError: invalid syntax
>>> 

「無効なシンタックス」としてエラーを返されました。なぜ??

調べてみると単純に、pip コマンドは python のシェルで実行するものでなくて、ターミナルを立ち上げた時のデフォルト(?)のコマンドラインで実行するものだと。

>>> pip install requests
  File "<stdin>", line 1
    pip install requests
        ^
SyntaxError: invalid syntax
>>> quit()

なので quit() と入力して一旦 python のシェルから脱出。

そしてpip install requests を再度入力。コレでOK。と思いきや。

エラー「zsh: command not found: pip」

>>> quit()
~ % pip install requests
zsh: command not found: pip

またもやエラー。「pip」というコマンドが見当たりませんと。

なんでや!!!

ということでまた調べたところ、自分は Macbook に python3 インストールして使っているので「pip」ではなく「pip3」を使う必要があったらしい。

「pip3 install requests」でインストール成功

というわけで改めて「pip3 install requests」と入力

そしたらようやく無事にインストール成功しました。

実際に requests モジュールを使ってみる

という事で再度ターミナルで「python3」と入力し Python を立ち上げ、下記を順に入力。

>>> import requests
>>> r = requests.get('http://yahoo.com/')
>>> r.text

そしてエンター!

>>> import requests
>>> r = requests.get('http://yahoo.com/')
>>> r.text
'<!DOCTYPE html>\n<html id="atomic" lang="en-US" class="atomic   l-out Pos-r https fp fp-v2 fp-default mini-uh-on uh-topbar-on ltr desktop Desktop bkt201">\n<head>\n    <meta http-equiv="X-UA-Compatible" content="IE=edge">\n    \n    <title>Yahoo</title><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="//s.yimg.com"><link rel="preconnect" href="//s.yimg.com">

とりあえずヤフーのソースコードがドバドバッと表示されたので、無事 requests モジュールを使える状態となりました!