国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 如何使用 Selenium 抓取受登錄保護的網站(分步指南)

如何使用 Selenium 抓取受登錄保護的網站(分步指南)

Nov 02, 2024 am 10:34 AM

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

我抓取受密碼保護的網站的步驟:

  1. 捕獲 HTML 表單元素:用戶名 ID、密碼 ID 和登錄按鈕類
  2. - 使用 requests 或 Selenium 等工具自動登錄:填寫用戶名,等待,填寫密碼,等待,點擊登錄
  3. - 存儲會話 cookie 以進行身份??驗證
  4. - 繼續(xù)抓取經過身份驗證的頁面

免責聲明:我已在 https://www.scrapewebapp.com/ 上為此特定用例構建了一個 API。因此,如果您想快速完成它,請使用它,否則請繼續(xù)閱讀。

讓我們使用這個例子:假設我想從我的帳戶 https://www.scrapewebapp.com/ 中抓取我自己的 API 密鑰。在此頁面上:https://app.scrapewebapp.com/account/api_key

1. 登錄頁面

首先,您需要找到登錄頁面。如果您嘗試訪問登錄后的頁面,大多數網站都會給您重定向 303,因此如果您嘗試直接抓取 https://app.scrapewebapp.com/account/api_key,您將自動獲取登錄頁面 https:// app.scrapewebapp.com/login。因此,如果尚未提供,這是自動查找登錄頁面的好方法。

好的,現(xiàn)在我們有了登錄頁面,我們需要找到添加用戶名或電子郵件以及密碼和實際登錄按鈕的位置。最好的方法是創(chuàng)建一個簡單的腳本,使用類型“電子郵件”、“用戶名”、“密碼”查找輸入的 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 實際登錄

現(xiàn)在您需要創(chuàng)建一個 selenium webdriver。我們將使用 chrome headless 來通過 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')

然后實際登錄我們的網站并保存 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. 從我們登錄的會話中獲取數據

在這部分中,我們將使用簡單的庫請求,但您也可以繼續(xù)使用 selenium。

現(xiàn)在我們想從此頁面獲取實際的 API:https://app.scrapewebapp.com/account/api_key。

因此,我們從請求庫創(chuàng)建一個會話并將每個 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 模型)這樣的人工智能。

這樣提示模型:“您是一名專家抓取工具,您只會提取從上下文中詢問的信息。我需要來自 {context} 的 api-key 值”

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 來實現(xiàn)這一切,請嘗試我的新產品 https://www.scrapewebapp.com/

如果你喜歡這篇文章,請給我鼓掌并關注我。確實有很大幫助!

以上是如何使用 Selenium 抓取受登錄保護的網站(分步指南)的詳細內容。更多信息請關注PHP中文網其他相關文章!

本站聲明
本文內容由網友自發(fā)貢獻,版權歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權的內容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅動的應用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Python的UNITDEST或PYTEST框架如何促進自動測試? Python的UNITDEST或PYTEST框架如何促進自動測試? Jun 19, 2025 am 01:10 AM

Python的unittest和pytest是兩種廣泛使用的測試框架,它們都簡化了自動化測試的編寫、組織和運行。1.二者均支持自動發(fā)現(xiàn)測試用例并提供清晰的測試結構:unittest通過繼承TestCase類并以test\_開頭的方法定義測試;pytest則更為簡潔,只需以test\_開頭的函數即可。2.它們都內置斷言支持:unittest提供assertEqual、assertTrue等方法,而pytest使用增強版的assert語句,能自動顯示失敗詳情。3.均具備處理測試準備與清理的機制:un

如何將Python用于數據分析和與Numpy和Pandas等文庫進行操作? 如何將Python用于數據分析和與Numpy和Pandas等文庫進行操作? Jun 19, 2025 am 01:04 AM

pythonisidealfordataanalysisionduetonumpyandpandas.1)numpyExccelSatnumericalComputationswithFast,多dimensionalArraysAndRaysAndOrsAndOrsAndOffectorizedOperationsLikenp.sqrt()

什么是動態(tài)編程技術,如何在Python中使用它們? 什么是動態(tài)編程技術,如何在Python中使用它們? Jun 20, 2025 am 12:57 AM

動態(tài)規(guī)劃(DP)通過將復雜問題分解為更簡單的子問題并存儲其結果以避免重復計算,來優(yōu)化求解過程。主要方法有兩種:1.自頂向下(記憶化):遞歸分解問題,使用緩存存儲中間結果;2.自底向上(表格化):從基礎情況開始迭代構建解決方案。適用于需要最大/最小值、最優(yōu)解或存在重疊子問題的場景,如斐波那契數列、背包問題等。在Python中,可通過裝飾器或數組實現(xiàn),并應注意識別遞推關系、定義基準情況及優(yōu)化空間復雜度。

如何使用__ITER__和__NEXT __在Python中實現(xiàn)自定義迭代器? 如何使用__ITER__和__NEXT __在Python中實現(xiàn)自定義迭代器? Jun 19, 2025 am 01:12 AM

要實現(xiàn)自定義迭代器,需在類中定義__iter__和__next__方法。①__iter__方法返回迭代器對象自身,通常為self,以兼容for循環(huán)等迭代環(huán)境;②__next__方法控制每次迭代的值,返回序列中的下一個元素,當無更多項時應拋出StopIteration異常;③需正確跟蹤狀態(tài)并設置終止條件,避免無限循環(huán);④可封裝復雜邏輯如文件行過濾,同時注意資源清理與內存管理;⑤對簡單邏輯可考慮使用生成器函數yield替代,但需結合具體場景選擇合適方式。

Python編程語言及其生態(tài)系統(tǒng)的新興趨勢或未來方向是什么? Python編程語言及其生態(tài)系統(tǒng)的新興趨勢或未來方向是什么? Jun 19, 2025 am 01:09 AM

Python的未來趨勢包括性能優(yōu)化、更強的類型提示、替代運行時的興起及AI/ML領域的持續(xù)增長。首先,CPython持續(xù)優(yōu)化,通過更快的啟動時間、函數調用優(yōu)化及擬議中的整數操作改進提升性能;其次,類型提示深度集成至語言與工具鏈,增強代碼安全性與開發(fā)體驗;第三,PyScript、Nuitka等替代運行時提供新功能與性能優(yōu)勢;最后,AI與數據科學領域持續(xù)擴張,新興庫推動更高效的開發(fā)與集成。這些趨勢表明Python正不斷適應技術變化,保持其領先地位。

如何使用插座在Python中執(zhí)行網絡編程? 如何使用插座在Python中執(zhí)行網絡編程? Jun 20, 2025 am 12:56 AM

Python的socket模塊是網絡編程的基礎,提供低級網絡通信功能,適用于構建客戶端和服務器應用。要設置基本TCP服務器,需使用socket.socket()創(chuàng)建對象,綁定地址和端口,調用.listen()監(jiān)聽連接,并通過.accept()接受客戶端連接。構建TCP客戶端需創(chuàng)建socket對象后調用.connect()連接服務器,再使用.sendall()發(fā)送數據和.recv()接收響應。處理多個客戶端可通過1.線程:每次連接啟動新線程;2.異步I/O:如asyncio庫實現(xiàn)無阻塞通信。注意事

Python類中的多態(tài)性 Python類中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向對象編程中的核心概念,指“一種接口,多種實現(xiàn)”,允許統(tǒng)一處理不同類型的對象。1.多態(tài)通過方法重寫實現(xiàn),子類可重新定義父類方法,如Animal類的speak()方法在Dog和Cat子類中有不同實現(xiàn)。2.多態(tài)的實際用途包括簡化代碼結構、增強可擴展性,例如圖形繪制程序中統(tǒng)一調用draw()方法,或游戲開發(fā)中處理不同角色的共同行為。3.Python實現(xiàn)多態(tài)需滿足:父類定義方法,子類重寫該方法,但不要求繼承同一父類,只要對象實現(xiàn)相同方法即可,這稱為“鴨子類型”。4.注意事項包括保持方

如何在Python中切片列表? 如何在Python中切片列表? Jun 20, 2025 am 12:51 AM

Python列表切片的核心答案是掌握[start:end:step]語法并理解其行為。1.列表切片的基本格式為list[start:end:step],其中start是起始索引(包含)、end是結束索引(不包含)、step是步長;2.省略start默認從0開始,省略end默認到末尾,省略step默認為1;3.獲取前n項用my_list[:n],獲取后n項用my_list[-n:];4.使用step可跳過元素,如my_list[::2]取偶數位,負step值可反轉列表;5.常見誤區(qū)包括end索引不

See all articles