美丽的汤刮刀

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

逐步实施

  • 网页抓取
  • 数据聚合
  • SEO审核

常见问题解答

为什么请求偶尔会失败?

如果站点具有严格的 CORS 标头,阻止浏览器获取操作,则该站点将会失败。 News.ycombinator 目前允许开放读取 CORS。

相关主题