検索
ホームページバックエンド開発Python チュートリアルSelenium を使用してログイン保護された Web サイトをスクレイピングする方法 (ステップバイステップガイド)

How to Scrape Login-Protected Websites with Selenium (Step by Step Guide)

パスワードで保護された Web サイトをスクレイピングする私の手順:

  1. HTML フォーム要素をキャプチャします: ユーザー名 ID、パスワード ID、ログイン ボタン クラス
  2. - リクエストや Selenium などのツールを使用してログインを自動化します: ユーザー名を入力し、待機し、パスワードを入力し、待機し、ログインをクリックします
  3. - 認証用にセッション Cookie を保存します
  4. - 認証されたページのスクレイピングを続行します

免責事項: この特定のユースケース用の API を https://www.scrapewebapp.com/ で構築しました。したがって、すぐに完了したい場合はこれを使用し、そうでない場合は読み続けてください。

この例を使用してみましょう: https://www.scrapewebapp.com/ にある自分のアカウントから自分の API キーをスクレイピングしたいとします。このページにあります: https://app.scrapewebapp.com/account/api_key

1. ログインページ

まず、ログイン ページを見つける必要があります。ほとんどの Web サイトでは、ログイン後のページにアクセスしようとするとリダイレクト 303 が発生するため、https://app.scrapewebapp.com/account/api_key を直接スクレイピングしようとすると、ログイン ページ https:// が自動的に取得されます。 app.scrapewebapp.com/login.したがって、ログイン ページがまだ提供されていない場合、ログイン ページの検索を自動化する良い方法です。

ログイン ページができたので、ユーザー名または電子メール、パスワード、および実際のサインイン ボタンを追加する場所を見つける必要があります。最善の方法は、タイプ「電子メール」、「ユーザー名」、「パスワード」を使用して入力の ID を検索し、タイプ「送信」のボタンを検索する単純なスクリプトを作成することです。以下のコードを作成しました:

from bs4 import BeautifulSoup


def extract_login_form(html_content: str):
    """
    Extracts the login form elements from the given HTML content and returns their CSS selectors.
    """
    soup = BeautifulSoup(html_content, "html.parser")

    # Finding the username/email field
    username_email = (
        soup.find("input", {"type": "email"})
        or soup.find("input", {"name": "username"})
        or soup.find("input", {"type": "text"})
    )  # Fallback to input type text if no email type is found

    # Finding the password field
    password = soup.find("input", {"type": "password"})

    # Finding the login button
    # Searching for buttons/input of type submit closest to the password or username field
    login_button = None

    # First try to find a submit button within the same form
    if password:
        form = password.find_parent("form")
        if form:
            login_button = form.find("button", {"type": "submit"}) or form.find(
                "input", {"type": "submit"}
            )
    # If no button is found in the form, fall back to finding any submit button
    if not login_button:
        login_button = soup.find("button", {"type": "submit"}) or soup.find(
            "input", {"type": "submit"}
        )

    # Extracting CSS selectors
    def generate_css_selector(element, element_type):
        if "id" in element.attrs:
            return f"#{element['id']}"
        elif "type" in element.attrs:
            return f"{element_type}[type='{element['type']}']"
        else:
            return element_type

    # Generate CSS selectors with the updated logic
    username_email_css_selector = None
    if username_email:
        username_email_css_selector = generate_css_selector(username_email, "input")

    password_css_selector = None
    if password:
        password_css_selector = generate_css_selector(password, "input")

    login_button_css_selector = None
    if login_button:
        login_button_css_selector = generate_css_selector(
            login_button, "button" if login_button.name == "button" else "input"
        )

    return username_email_css_selector, password_css_selector, login_button_css_selector


def main(html_content: str):
    # Call the extract_login_form function and return its result
    return extract_login_form(html_content)

2. Selenium を使用して実際にログインする

次に、Selenium Web ドライバーを作成する必要があります。 Chrome ヘッドレスを使用して Python で実行します。インストール方法は次のとおりです:

# Install selenium and chromium

!pip install selenium
!apt-get update 
!apt install chromium-chromedriver

!cp /usr/lib/chromium-browser/chromedriver /usr/bin
import sys
sys.path.insert(0,'/usr/lib/chromium-browser/chromedriver')

次に、実際に当社の Web サイトにログインし、Cookie を保存します。すべての Cookie は保存されますが、必要に応じて認証 Cookie のみを保存することもできます。

# Imports
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import time

# Set up Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')

# Initialize the WebDriver
driver = webdriver.Chrome(options=chrome_options)

try:
    # Open the login page
    driver.get("https://app.scrapewebapp.com/login")

    # Find the email input field by ID and input your email
    email_input = driver.find_element(By.ID, "email")
    email_input.send_keys("******@gmail.com")

    # Find the password input field by ID and input your password
    password_input = driver.find_element(By.ID, "password")
    password_input.send_keys("*******")

    # Find the login button and submit the form
    login_button = driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
    login_button.click()

    # Wait for the login process to complete
    time.sleep(5)  # Adjust this depending on your site's response time


finally:
    # Close the browser
    driver.quit()

3. Cookie を保存する

driver.getcookies() 関数から辞書に保存するだけで簡単です。

def save_cookies(driver):
    """Save cookies from the Selenium WebDriver into a dictionary."""
    cookies = driver.get_cookies()
    cookie_dict = {}
    for cookie in cookies:
        cookie_dict[cookie['name']] = cookie['value']
    return cookie_dict

WebDriver から Cookie を保存します

cookie = save_cookies(ドライバー)

4. ログインセッションからデータを取得する

このパートでは、単純なライブラリ リクエストを使用しますが、引き続き Selenium を使用することもできます。

次に、このページから実際の API を取得します: https://app.scrapewebapp.com/account/api_key.

そこで、リクエスト ライブラリからセッションを作成し、そこに各 Cookie を追加します。次に、URL をリクエストし、応答テキストを出力します。

def scrape_api_key(cookies):
    """Use cookies to scrape the /account/api_key page."""
    url = 'https://app.scrapewebapp.com/account/api_key'

    # Set up the session to persist cookies
    session = requests.Session()

    # Add cookies from Selenium to the requests session
    for name, value in cookies.items():
        session.cookies.set(name, value)

    # Make the request to the /account/api_key page
    response = session.get(url)

    # Check if the request is successful
    if response.status_code == 200:
        print("API Key page content:")
        print(response.text)  # Print the page content (could contain the API key)
    else:
        print(f"Failed to retrieve API key page, status code: {response.status_code}")

5. 必要な実際のデータを取得する (ボーナス)

必要なページテキストは得られましたが、気にしないデータがたくさんあります。必要なのは api_key だけです。

これを行うための最良かつ最も簡単な方法は、ChatGPT (GPT4o モデル) のような AI を使用することです。

モデルに次のようなプロンプトを出します。「あなたはスクレーパーの専門家であり、コンテキストから要求された情報のみを抽出します。 {context} からの API キーの値が必要です」

from bs4 import BeautifulSoup


def extract_login_form(html_content: str):
    """
    Extracts the login form elements from the given HTML content and returns their CSS selectors.
    """
    soup = BeautifulSoup(html_content, "html.parser")

    # Finding the username/email field
    username_email = (
        soup.find("input", {"type": "email"})
        or soup.find("input", {"name": "username"})
        or soup.find("input", {"type": "text"})
    )  # Fallback to input type text if no email type is found

    # Finding the password field
    password = soup.find("input", {"type": "password"})

    # Finding the login button
    # Searching for buttons/input of type submit closest to the password or username field
    login_button = None

    # First try to find a submit button within the same form
    if password:
        form = password.find_parent("form")
        if form:
            login_button = form.find("button", {"type": "submit"}) or form.find(
                "input", {"type": "submit"}
            )
    # If no button is found in the form, fall back to finding any submit button
    if not login_button:
        login_button = soup.find("button", {"type": "submit"}) or soup.find(
            "input", {"type": "submit"}
        )

    # Extracting CSS selectors
    def generate_css_selector(element, element_type):
        if "id" in element.attrs:
            return f"#{element['id']}"
        elif "type" in element.attrs:
            return f"{element_type}[type='{element['type']}']"
        else:
            return element_type

    # Generate CSS selectors with the updated logic
    username_email_css_selector = None
    if username_email:
        username_email_css_selector = generate_css_selector(username_email, "input")

    password_css_selector = None
    if password:
        password_css_selector = generate_css_selector(password, "input")

    login_button_css_selector = None
    if login_button:
        login_button_css_selector = generate_css_selector(
            login_button, "button" if login_button.name == "button" else "input"
        )

    return username_email_css_selector, password_css_selector, login_button_css_selector


def main(html_content: str):
    # Call the extract_login_form function and return its result
    return extract_login_form(html_content)

これらすべてをシンプルで信頼性の高い API で実現したい場合は、私の新製品 https://www.scrapewebapp.com/

を試してみてください。

この投稿が気に入ったら、拍手とフォローをお願いします。とても役に立ちます!

以上がSelenium を使用してログイン保護された Web サイトをスクレイピングする方法 (ステップバイステップガイド)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonリストをどのようにスライスしますか?Pythonリストをどのようにスライスしますか?May 02, 2025 am 12:14 AM

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

Numpyアレイで実行できる一般的な操作は何ですか?Numpyアレイで実行できる一般的な操作は何ですか?May 02, 2025 am 12:09 AM

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Pythonを使用したデータ分析では、配列はどのように使用されていますか?Pythonを使用したデータ分析では、配列はどのように使用されていますか?May 02, 2025 am 12:09 AM

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?May 02, 2025 am 12:08 AM

listsandnumpyarraysinpythonhavedifferentmemoryfootprints:listsaremoreflexiblellessmemory-efficient、whileenumpyarraysaraysareoptimizedfornumericaldata.1)listsstorereferencesto objects、with whowedaround64byteson64-bitedatigu

実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehaveCorrectlyAcrossDevelosment、staging、and Production、usetheseStrategies:1)環境variablesforsimplestetings、2)configurationfilesforcomplexsetups、and3)dynamicloadingforadaptability.eachtododododododofersuniquebentandrequiresca

Pythonアレイをどのようにスライスしますか?Pythonアレイをどのようにスライスしますか?May 01, 2025 am 12:18 AM

Pythonリストスライスの基本的な構文はリストです[start:stop:step]。 1.STARTは最初の要素インデックス、2。ストップは除外された最初の要素インデックスであり、3.ステップは要素間のステップサイズを決定します。スライスは、データを抽出するためだけでなく、リストを変更および反転させるためにも使用されます。

どのような状況で、リストは配列よりもパフォーマンスが向上しますか?どのような状況で、リストは配列よりもパフォーマンスが向上しますか?May 01, 2025 am 12:06 AM

ListSoutPerformArraysIn:1)ダイナミシジョンアンドフレーケンティオン/削除、2)ストーリングヘテロゼンダタ、および3)メモリ効率の装飾、ButmayhaveslightPerformancostsinceNASOPERATIONS。

PythonアレイをPythonリストに変換するにはどうすればよいですか?PythonアレイをPythonリストに変換するにはどうすればよいですか?May 01, 2025 am 12:05 AM

toconvertapythonarraytoalist、usetheList()constructororageneratorexpression.1)importhearraymoduleandcreateanarray.2)useList(arr)または[xforxinarr] toconvertoalistは、largedatatessを変えることを伴うものです。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。