Pythonでスクレイピングをしたいがrequests.get()の段階でエラーが出る
Q&A
Closed
解決したいこと
Pythonでスクレイピングをしたい
下記ページからそれぞれの活動記録のページへアクセスし、
ページ中にある「エクスポート」ボタンからダウンロードできる
GPXファイルをまとめてダウンロードしたい。
https://yamap.com/search/activities
なお、GPXファイルのダウンロードはプレミアム会員のみ可能ですが、
当方プレミアム会員のアカウントを所持しています。
発生している問題・エラー
import requests
url = "https://yamap.com/search/activities"
response = requests.get(url)
GPXファイル収集のためコードを書いていましたが、
上記の段階で下記エラーが出ることが発覚。
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/urllib3/connectionpool.py:711, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    710 if is_new_proxy_conn and http_tunnel_required:
--> 711     self._prepare_proxy(conn)
    713 # Make the request on the httplib connection object.
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/urllib3/connectionpool.py:1007, in HTTPSConnectionPool._prepare_proxy(self, conn)
   1005     conn.tls_in_tls_required = True
-> 1007 conn.connect()
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/urllib3/connection.py:374, in HTTPSConnection.connect(self)
    372 # Calls self._set_hostport(), so self.host is
    373 # self._tunnel_host below.
--> 374 self._tunnel()
    375 # Mark this connection as not reusable
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/http/client.py:926, in HTTPConnection._tunnel(self)
    925     self.close()
--> 926     raise OSError(f"Tunnel connection failed: {code} {message.strip()}")
    927 while True:
OSError: Tunnel connection failed: 403 Forbidden
During handling of the above exception, another exception occurred:
MaxRetryError                             Traceback (most recent call last)
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/requests/adapters.py:486, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
    485 try:
--> 486     resp = conn.urlopen(
    487         method=request.method,
    488         url=url,
    489         body=request.body,
    490         headers=request.headers,
    491         redirect=False,
    492         assert_same_host=False,
    493         preload_content=False,
    494         decode_content=False,
    495         retries=self.max_retries,
    496         timeout=timeout,
    497         chunked=chunked,
    498     )
    500 except (ProtocolError, OSError) as err:
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/urllib3/connectionpool.py:798, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    796     e = ProtocolError("Connection aborted.", e)
--> 798 retries = retries.increment(
    799     method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
    800 )
    801 retries.sleep()
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/urllib3/util/retry.py:592, in Retry.increment(self, method, url, response, error, _pool, _stacktrace)
    591 if new_retry.is_exhausted():
--> 592     raise MaxRetryError(_pool, url, error or ResponseError(cause))
    594 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
MaxRetryError: HTTPSConnectionPool(host='yamap.com', port=443): Max retries exceeded with url: /activities/ (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))
During handling of the above exception, another exception occurred:
ProxyError                                Traceback (most recent call last)
Cell In[75], line 7
      4 import shutil
      6 url = "https://yamap.com/activities/"
----> 7 response = requests.get(url)
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/requests/api.py:73, in get(url, params, **kwargs)
     62 def get(url, params=None, **kwargs):
     63     r"""Sends a GET request.
     64 
     65     :param url: URL for the new :class:`Request` object.
   (...)
     70     :rtype: requests.Response
     71     """
---> 73     return request("get", url, params=params, **kwargs)
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/requests/api.py:59, in request(method, url, **kwargs)
     55 # By using the 'with' statement we are sure the session is closed, thus we
     56 # avoid leaving sockets open which can trigger a ResourceWarning in some
     57 # cases, and look like a memory leak in others.
     58 with sessions.Session() as session:
---> 59     return session.request(method=method, url=url, **kwargs)
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/requests/sessions.py:589, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    584 send_kwargs = {
    585     "timeout": timeout,
    586     "allow_redirects": allow_redirects,
    587 }
    588 send_kwargs.update(settings)
--> 589 resp = self.send(prep, **send_kwargs)
    591 return resp
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/requests/sessions.py:703, in Session.send(self, request, **kwargs)
    700 start = preferred_clock()
    702 # Send the request
--> 703 r = adapter.send(request, **kwargs)
    705 # Total elapsed time of the request (approximately)
    706 elapsed = preferred_clock() - start
File /opt/conda/envs/anaconda-panel-2023.05-py310/lib/python3.11/site-packages/requests/adapters.py:513, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
    510     raise RetryError(e, request=request)
    512 if isinstance(e.reason, _ProxyError):
--> 513     raise ProxyError(e, request=request)
    515 if isinstance(e.reason, _SSLError):
    516     # This branch is for urllib3 v1.22 and later.
    517     raise SSLError(e, request=request)
ProxyError: HTTPSConnectionPool(host='yamap.com', port=443): Max retries exceeded with url: /activities/ (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 403 Forbidden')))
urlを「https://yahoo.com/」に変更するとエラーは出ません。
ファイル収集先のYAMAPの利用規約にはスクレイピング禁止の旨は記載されておらず、
YAMAP側からスクレイピングにガードを掛けているようには思えません。
自分で試したこと
import requests
url = "https://yamap.com/search/activities"
user_agent = 'Mozilla/5.0'
response = requests.get(url, headers={"User-Agent": user_agent})
調べてみたところ、ユーザエージェントを設定すると
エラーが解消される可能性があるとのことで、
上記のコードを実行しましたが、結果は同じでした。
2024/06/30 15:11追記
様々なURLを試してみましたが、https://yahoo.com 、https://google.com くらいしかエラーが出ないURLがありませんでした。
JupiterNotebookから実行していますが、なにか関係ありますかね…?
2024/07/01 15:01追記
一応解決(?)しました。
ご回答者様から「モジュールのインストール時はプロキシエラーが出ないのか」とご質問いただいたきました。
コードの実行はJupiterNotebookから、
モジュールのインストールはAnaconda Promptから行っておりましたが、
モジュールインストール時にはプロキシエラーは出ていなかったため、
Anaconda Promptからコードを実行してみたところ、
なぜかエラーは出ませんでした。
JupiterNotebookだとなぜエラーが出るのか、原因は不明ですが、とりあえず動くようになったのでクローズさせていただきます。
ご回答くださったみなさんありがとうございました。





