비밀번호로 보호된 웹사이트를 긁어내는 단계:
- HTML 양식 요소 캡처: 사용자 이름 ID, 비밀번호 ID 및 로그인 버튼 클래스
- - 요청이나 Selenium과 같은 도구를 사용하여 로그인을 자동화합니다. 사용자 이름 입력, 대기, 비밀번호 입력, 대기, 로그인 클릭
- - 인증을 위해 세션 쿠키 저장
- - 인증된 페이지 계속 스크랩
면책조항: https://www.scrapewebapp.com/에서 이 특정 사용 사례에 대한 API를 구축했습니다. 따라서 빨리 끝내고 싶다면 사용하고, 아니면 계속 읽어보세요.
이 예를 사용하겠습니다. 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. 따라서 아직 제공되지 않은 경우 로그인 페이지 찾기를 자동화하는 좋은 방법입니다.
자, 이제 로그인 페이지가 생겼으니 사용자 이름이나 이메일, 비밀번호, 실제 로그인 버튼을 추가할 위치를 찾아야 합니다. 가장 좋은 방법은 "이메일", "사용자 이름", "비밀번호" 유형을 사용하여 입력의 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 Webdriver를 만들어야 합니다. Python으로 실행하기 위해 Chrome Headless를 사용할 것입니다. 설치 방법은 다음과 같습니다.
# 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')
그런 다음 실제로 당사 웹사이트에 로그인하여 쿠키를 저장하세요. 모든 쿠키는 저장되지만 인증 쿠키는 원하는 경우에만 저장할 수 있습니다.
# 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. 쿠키 저장
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에서 쿠키를 저장하세요
쿠키 = save_cookies(드라이버)
4. 로그인한 세션에서 데이터 가져오기
이 부분에서는 간단한 라이브러리 요청을 사용하지만 셀레늄을 계속 사용해도 됩니다.
이제 다음 페이지에서 실제 API를 얻으려고 합니다: https://app.scrapewebapp.com/account/api_key.
그래서 요청 라이브러리에서 세션을 생성하고 여기에 각 쿠키를 추가합니다. 그런 다음 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을 사용하여 로그인으로 보호된 웹사이트를 긁는 방법(단계별 가이드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

이 기사에서는 HTML을 구문 분석하기 위해 파이썬 라이브러리 인 아름다운 수프를 사용하는 방법을 설명합니다. 데이터 추출, 다양한 HTML 구조 및 오류 처리 및 대안 (SEL과 같은 Find (), find_all (), select () 및 get_text ()와 같은 일반적인 방법을 자세히 설명합니다.

파이썬 객체의 직렬화 및 사막화는 사소한 프로그램의 주요 측면입니다. 무언가를 Python 파일에 저장하면 구성 파일을 읽거나 HTTP 요청에 응답하는 경우 객체 직렬화 및 사태화를 수행합니다. 어떤 의미에서, 직렬화와 사제화는 세계에서 가장 지루한 것들입니다. 이 모든 형식과 프로토콜에 대해 누가 걱정합니까? 일부 파이썬 객체를 지속하거나 스트리밍하여 나중에 완전히 검색하려고합니다. 이것은 세상을 개념적 차원에서 볼 수있는 좋은 방법입니다. 그러나 실제 수준에서 선택한 직렬화 체계, 형식 또는 프로토콜은 속도, 보안, 유지 보수 상태 및 프로그램의 기타 측면을 결정할 수 있습니다.

이 기사는 딥 러닝을 위해 텐서 플로와 Pytorch를 비교합니다. 데이터 준비, 모델 구축, 교육, 평가 및 배포와 관련된 단계에 대해 자세히 설명합니다. 프레임 워크, 특히 계산 포도와 관련하여 주요 차이점

Python의 통계 모듈은 강력한 데이터 통계 분석 기능을 제공하여 생물 통계 및 비즈니스 분석과 같은 데이터의 전반적인 특성을 빠르게 이해할 수 있도록 도와줍니다. 데이터 포인트를 하나씩 보는 대신 평균 또는 분산과 같은 통계를보고 무시할 수있는 원래 데이터에서 트렌드와 기능을 발견하고 대형 데이터 세트를보다 쉽고 효과적으로 비교하십시오. 이 튜토리얼은 평균을 계산하고 데이터 세트의 분산 정도를 측정하는 방법을 설명합니다. 달리 명시되지 않는 한,이 모듈의 모든 함수는 단순히 평균을 합산하는 대신 평균 () 함수의 계산을 지원합니다. 부동 소수점 번호도 사용할 수 있습니다. 무작위로 가져옵니다 수입 통계 Fracti에서

이 튜토리얼은 간단한 나무 탐색을 넘어서 DOM 조작에 중점을 둔 아름다운 수프에 대한 이전 소개를 바탕으로합니다. HTML 구조를 수정하기위한 효율적인 검색 방법과 기술을 탐색하겠습니다. 일반적인 DOM 검색 방법 중 하나는 EX입니다

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

이 기사는 Python 개발자가 CLIS (Command-Line Interfaces) 구축을 안내합니다. Typer, Click 및 Argparse와 같은 라이브러리를 사용하여 입력/출력 처리를 강조하고 CLI 유용성을 향상시키기 위해 사용자 친화적 인 디자인 패턴을 홍보하는 세부 정보.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

Dreamweaver Mac版
시각적 웹 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음
