크롤러 기술의 기본 개념
크롤러: 네트워크 데이터를 자동으로 얻는 프로그램입니다.
웹 페이지 구조: HTML, CSS, JavaScript 등
HTTP 요청: 클라이언트가 서버에 데이터를 요청하는 방법입니다.
HTTP 응답: 서버가 클라이언트에 반환하는 데이터입니다.
요청 및 응답
Python의 요청 라이브러리를 사용하여 HTTP 요청을 보냅니다.
import requests url = "https://www.example.com" response = requests.get(url)
응답 콘텐츠 가져오기
html_content = response.text
HTML 구문 분석 및 데이터 추출
BeautifulSoup 라이브러리를 사용하여 HTML 콘텐츠를 구문 분석하세요.
from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, "html.parser")
CSS 선택기나 기타 방법을 사용하여 데이터를 추출하세요.
title = soup.title.string
실전 전투: Jianshu 웹사이트 홈페이지의 기사 정보를 크롤링
Jianshu 웹사이트 홈페이지의 HTML 콘텐츠를 얻기 위해 요청을 보냅니다.
import requests from bs4 import BeautifulSoup url = "https://www.jianshu.com" response = requests.get(url) html_content = response.text
데이터 저장
데이터를 JSON 형식으로 저장합니다.
import json with open("jianshu_articles.json", "w", encoding="utf-8") as f: json.dump(article_info_list, f, ensure_ascii=False, indent=4)
테스트 및 최적화
1. 크롤러 방지 전략을 접할 때 User-Agent를 사용하여 브라우저인 것처럼 가장할 수 있습니다.
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} response = requests.get(url, headers=headers)
2. time.sleep() 함수를 사용하여 요청 빈도를 제어하세요.
import time time.sleep(10)
3. 오류 처리 및 예외 포착.
try: response = requests.get(url, headers=headers, timeout=5) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error: {e}")
웹사이트 크롤러의 전체 코드:
import requests from bs4 import BeautifulSoup import json import time def fetch_jianshu_articles(): url = "https://www.jianshu.com" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} try: response = requests.get(url, headers=headers, timeout=5) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error: {e}") return html_content = response.text soup = BeautifulSoup(html_content, "html.parser") articles = soup.find_all("div", class_="content") article_info_list = [] for article in articles: title = article.h3.text.strip() author = article.find("span", class_="name").text.strip() link = url + article.h3.a["href"] article_info = {"title": title, "author": author, "link": link} article_info_list.append(article_info) return article_info_list def save_to_json(article_info_list, filename): with open(filename, "w", encoding="utf-8") as f: json.dump(article_info_list, f, ensure_ascii=False, indent=4) if __name__ == "__main__": article_info_list = fetch_jianshu_articles() if article_info_list: save_to_json(article_info_list, "jianshu_articles.json") print("Jianshu articles saved to 'jianshu_articles.json'.") else: print("Failed to fetch Jianshu articles.")
보충
이 실용적인 프로젝트를 더 잘 이해하려면 Python의 네트워크 프로그래밍 및 크롤러 기술을 익히는 데 도움이 되는 몇 가지 기본 개념과 원칙을 이해해야 합니다. 다음은 몇 가지 기본 웹 크롤링 개념입니다.
HTTP 프로토콜: HTTP(Hypertext Transfer Protocol)는 HTML과 같은 하이퍼미디어 문서를 전송하는 데 사용되는 애플리케이션 계층 프로토콜입니다. HTTP 프로토콜은 웹 서버에서 웹 브라우저 또는 다른 클라이언트로 데이터를 전송하거나 게시하는 데 사용됩니다.
HTML, CSS 및 JavaScript: HTML은 웹 페이지를 설명하는 데 사용되는 언어입니다. CSS는 HTML의 구조를 표현하는 데 사용되는 스타일입니다. JavaScript는 웹 프로그래밍을 위한 스크립팅 언어로, 주로 웹 페이지에 동적 효과를 구현하고 사용자와 상호 작용하는 데 사용됩니다.
DOM: DOM(문서 개체 모델)은 HTML 및 XML 문서를 처리하기 위한 크로스 플랫폼 프로그래밍 인터페이스입니다. DOM은 문서를 트리 구조로 취급합니다. 여기서 각 노드는 부분(예: 요소, 속성 또는 텍스트)을 나타냅니다.
URL: URL(Uniform Resource Locator)은 인터넷 리소스의 위치를 지정하는 데 사용되는 문자열입니다.
요청 헤더: HTTP 요청에서 요청 헤더에는 클라이언트 환경, 브라우저 등에 대한 정보가 포함됩니다. 일반적인 요청 헤더 필드에는 User-Agent, Accept, Referer 등이 포함됩니다.
응답 헤더: HTTP 응답에서 응답 헤더에는 서버에 대한 정보, 응답 상태 코드 및 기타 정보가 포함됩니다. 일반적인 응답 헤더 필드에는 Content-Type, Content-Length, Server 등이 포함됩니다.
웹 크롤러 전략: 일부 웹사이트에서는 크롤러가 데이터를 크롤링하는 것을 방지하기 위해 IP 차단, 액세스 속도 제한, JavaScript를 사용하여 데이터를 동적으로 로드하는 등 몇 가지 전략을 채택합니다. 실제 응용 프로그램에서는 프록시 IP 사용, 크롤러 크롤링 속도 제한, 브라우저 시뮬레이션 라이브러리(예: Selenium) 사용 등과 같은 전략을 기반으로 해당 대응 조치를 취해야 합니다.
위 내용은 Python 크롤러 기술 도입 예시 코드 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

"for"and "while"loopsare : 1) "에 대한"loopsareIdealforitertatingOverSorkNowniterations, whide2) "weekepindiTeRations.Un

Python에서는 다양한 방법을 통해 목록을 연결하고 중복 요소를 관리 할 수 있습니다. 1) 연산자를 사용하거나 ()을 사용하여 모든 중복 요소를 유지합니다. 2) 세트로 변환 한 다음 모든 중복 요소를 제거하기 위해 목록으로 돌아가지 만 원래 순서는 손실됩니다. 3) 루프 또는 목록 이해를 사용하여 세트를 결합하여 중복 요소를 제거하고 원래 순서를 유지하십시오.

fastestestestedforListCancatenationInpythondSpendsonListsize : 1) Forsmalllist, OperatoriseFficient.2) ForlargerLists, list.extend () OrlistComprehensionIsfaster, withextend () morememory-efficientBymodingListsin-splace.

toInsertElmentsIntoapyThonList, useAppend () toaddtotheend, insert () foraspecificposition, andextend () andextend () formultipleElements.1) useappend () foraddingsingleitemstotheend.2) useinsert () toaddatespecificindex, 그러나)

pythonlistsareimplementedesdynamicarrays, notlinkedlists.1) thearestoredIntIguousUousUousUousUousUousUousUousUousUousInSeripendExeDaccess, LeadingSpyTHOCESS, ImpactingEperformance

PythonoffersfourmainmethodstoremoveElementsfromalist : 1) 제거 (값) 제거 (값) removesthefirstoccurrencefavalue, 2) pop (index) 제거 elementatAspecifiedIndex, 3) delstatemeveselementsByindexorSlice, 4) RemovesAllestemsfromTheChmetho

Toresolvea "permissionDenied"오류가 발생할 때 오류가 발생합니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

드림위버 CS6
시각적 웹 개발 도구

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

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경