美しいスープスクレーパー
micropip/requests 経由で 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 のオープン読み取りを許可しています。