BeautifulSoup Scraper

透過 micropip/requests 取得並解析 HTML。

在編輯器中嘗試

概述

雖然請求通常需要本機作業系統套接字,但PyRun透過瀏覽器取得 API 映射請求功能。

這允許解析開啟的 CORS 頁面。

程式碼和執行輸出

動態抓取駭客新聞頭條新聞。

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: ...

逐步實施

  • 網頁抓取
  • Data Aggregation
  • SEO Auditing

常見問題解答

為什麼請求偶爾會失敗?

如果網站具有嚴格的 CORS 標頭,阻止瀏覽器取得操作,則該網站將會失敗。 News.ycombinator 目前允許開放讀取 CORS。

相關主題