아름다운수프 스크레이퍼
micropip/요청을 통해 HTML을 가져오고 구문 분석합니다.
개요
요청에는 일반적으로 로컬 OS 소켓이 필요하지만PyRun는 브라우저 가져오기 API를 통해 요청 기능을 매핑합니다.
이를 통해 열려 있는 CORS 페이지를 구문 분석할 수 있습니다.
코드 및 실행 출력
Hacker News의 주요 뉴스 헤드라인을 동적으로 스크랩합니다.
scraper.py
에디터에서 사용해 보세요import requests
from bs4 import BeautifulSoup
# PyRun uses micropip internally to make requests
# through the browser's fetch API
url = 'https://news.ycombinator.com'
print(f"Fetching {url}...\n")
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print("=== Hacker News Top Stories ===")
# Find the story titles
titles = soup.find_all('span', class_='titleline', limit=5)
for i, title in enumerate(titles):
link = title.find('a')
text = link.text
href = link.get('href')
print(f"{i+1}. {text}")
print(f" Link: {href}\n")터미널 출력
Fetching https://news.ycombinator.com...
=== Hacker News Top Stories ===
1. ...
Link: ...
2. ...
Link: ...단계별 구현
- 웹 스크래핑
- 데이터 집계
- SEO 감사
자주 묻는 질문
요청이 때때로 실패하는 이유는 무엇입니까?
사이트에 브라우저 가져오기 작업을 방지하는 엄격한 CORS 헤더가 있는 경우 사이트는 실패합니다. News.ycombinator는 현재 공개 읽기 CORS를 허용합니다.