6
6

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 3 years have passed since last update.

【Python】Webスクレイピングで403 Forbidden(You don't have permission to access)が出た場合の対処法(備忘録)

Last updated at Posted at 2021-03-20

自分用メモ

スクレイピング対象サイトへの初回アクセスで403 Forbiddenが発生した場合、リクエストのHTTPヘッダに**ユーザーエージェント(User Agent)**がないことがエラー原因として考えられる。

エラーになったコード

from bs4 import BeautifulSoup
import requests

# URLからrequestsのresponseを取得
url = "https://○○○○/○○○○/○○○○/"
response = requests.get(url)

# BeautifulSoupの初期化
soup = BeautifulSoup(response.text, 'html.parser')

# HTMLをインデントして取得
html = soup.prettify()

# インデントされたHTMLをファイル出力
f = open('prettify.html', 'w', encoding='UTF-8') 
f.write(html)
f.close()

返却されたHTML(403 Forbidden)

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
 <head>
  <title>
   403 Forbidden
  </title>
 </head>
 <body>
  <h1>
   Forbidden
  </h1>
  <p>
   You don't have permission to access /○○○○/○○○○/○○○○/
on this server.
  </p>
 </body>
</html>

403 Forbidden(You don't have permission to access)を出さないポイント

HTTPヘッダにユーザーエージェント(User Agent)を設定してあげる。

url = "https://○○○○/○○○○/○○○○/"
dummy_user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'
response = requests.get(url, headers={"User-Agent": dummy_user_agent})

HTML情報が取得出来たコード

from bs4 import BeautifulSoup
import requests

# URLからrequestsのresponseを取得
url = "https://○○○○/○○○○/○○○○/"
dummy_user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'
response = requests.get(url, headers={"User-Agent": dummy_user_agent})


# BeautifulSoupの初期化
soup = BeautifulSoup(response.text, 'html.parser')

# HTMLをインデントして取得
html = soup.prettify()

# インデントされたHTMLをファイル出力
f = open('prettify.html', 'w', encoding='UTF-8') 
f.write(html)
f.close()

参考リンク
mozilla Doc

以上

6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?