LoginSignup
20
16

More than 3 years have passed since last update.

Selenium+Headless Chromeで“Access Denied”となるページをスクレイピングする方法

Last updated at Posted at 2020-02-18

はじめに

Selenium + Headless Chromeでスクレイピングをしていると、headモードでは情報が取得できるのに、headlessにした途端に、NoSuchElementExceptionのエラーが発生するサイトに出会いました。
回避策について日本語の記事が少なかったので投稿してみようと思います。

状況

・headモードではスクレイピングができます。
・headlessオプションを追加にした途端にNoSuchElementExceptionが発生しました。

デバッグ

原因究明

要素が取得できていないようなので、driver.page_sourceで当該サイトのソースを確認してみました。

scraping.py
driver.page_source

返ってきた HTMLには"Access Denied"の文字が、headlessからのアクセスは拒否されるようです。

<html><head>
webapp_1        | <title>Access Denied</title>
webapp_1        | </head><body>
webapp_1        | <h1>Access Denied</h1>
webapp_1        |  
webapp_1        | You don't have permission to access "http://www.xxxxxxx/" on this server.<p>

対策

調べてみると、chromedriverにはブラウザからのアクセスを装うことができるuser_agentオプションがありました。こちらをchromedrivereのオプションに追加することで無事に要素が取得できるようになりました。

scraping.py
options = webdriver.ChromeOptions()
            options.binary_location = '/usr/bin/google-chrome'
            options.add_argument('--no-sandbox')
            options.add_argument('--headless')
            options.add_argument('--disable-gpu')
            options.add_argument('--lang=ja-JP')
            options.add_argument(f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36') #追加


以上

20
16
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
20
16