
区块链API推荐,快速开发去中心化应用
Python 开发人员可以访问一些可用的最佳 Web 抓取库和框架。让我们一起来了解它们的作用以及何时使用它们。
Web 抓取是自动化提取网页数据的关键方法,Python 拥有多个库和框架帮助您完成这一过程。以下是围绕Python 中最受欢迎的 Web 抓取库和框架:它们的功能、优缺点、替代方案和代码示例。
帮助您确切地知道使用什么工具来处理过程中可能遇到的任何 Web 抓取项目。
Crawlee是一个功能全面的Web抓取和浏览器自动化工具,旨在助力用户迅速构建可靠的爬虫系统。该工具最初于2022年夏天为Node.js和TypeScript用户推出,而Crawlee for Python版本则在2024年7月面世,并迅速在GitHub上收获了超过3,500颗星的关注。
✨ 特征
👍 优点
👎 缺点
🤔 选择
Scrapy, Playwright, Beautiful Soup
🔰 安装 Crawlee
要开始使用 Crawlee for Python,请运行以下命令:
pipx run crawlee create my-crawler
📜 代码示例
import asyncio
from crawlee.playwright_crawler import PlaywrightCrawler, PlaywrightCrawlingContext
async def main() -> None:
# Create a crawler instance
crawler = PlaywrightCrawler(
# headless=False,
# browser_type='firefox',
)
@crawler.router.default_handler
async def request_handler(context: PlaywrightCrawlingContext) -> None:
data = {
"request_url": context.request.url,
"page_url": context.page.url,
"page_title": await context.page.title(),
"page_content": (await context.page.content())[:10000],
}
await context.push_data(data)
await crawler.run(["https://crawlee.dev"])
if __name__ == "__main__":
asyncio.run(main())
使用Crawlee的PlaywrightCrawler抓取网站标题及内容示例
每个网络抓取任务的首要步骤都是向目标网站发送请求并获取其内容,这些内容通常为HTML格式。Python中的Requests库正是为此而生,它凭借“HTTP for humans”的核心理念,极大地简化了这一过程,因此成为了下载次数最多的Python包。
✨ 特征
👍 优点
👎 缺点
http.client
、urllib3
),更适用于那些性能敏感的应用程序。asyncio
、aiohttp
等库来实现非阻塞请求,增加了开发复杂度。🤔 选择
httpx, urlib3, http.client, aiohttp
🔰 安装请求
要安装 Requests 库,请使用 Python 包管理器 pip:
pip install requests
📜 代码示例
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json() # Parse JSON response
print(data)
else:
print(f"Request failed with status code: {response.status_code}")
HTTPX 作为新一代 HTTP 库,相较于 Requests,提供了异步和 HTTP/2 等高级功能。如异步和 HTTP/2 支持。HTTPX 在核心功能与 Requests 保持高度一致,易于上手。鉴于其高性能与良好的扩展性,HTTPX 不仅适用于大型项目,也推荐用于小型项目,为未来可能的需求扩展预留空间。
✨ 特征
asyncio
内置功能,实现非阻塞 HTTP 请求,提升效率。👍 优点
👎 缺点
🤔 选择
Requests, aiohttp, urlib3, http.client
🔰 安装 HTTPX
要安装 HTTPX 库,请使用 Python 包管理器 pip:
pip install httpx
📜 代码示例
import httpx
import asyncio
async def fetch_data():
async with httpx.AsyncClient() as client:
response = await client.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json() # Parse JSON response
print(data)
else:
print(f"Request failed with status code: {response.status_code}")
# Run the asynchronous function
asyncio.run(fetch_data())
一旦你拥有 HTML 内容,你需要一种方法去解析它并提取你感兴趣的数据。为此,Beautiful Soup这一流行的Python HTML解析器应运而生。它允许你在HTML树结构中轻松导航和搜索,从而获取你感兴趣的数据。其简单的语法和简单的设置也使 Beautiful Soup 成为中小型 Web 抓取项目和 Web 抓取初学者的绝佳选择。
✨ 特征
👍 优点
👎 缺点
🤔 选择
lxml、html5lib
🔰 安装 Beautiful Soup
为了安装Beautiful Soup,请使用pip来安装相应的软件包。此外,为了获得更佳的解析功能,我们还建议安装lxml或html5lib。这些库与beautifulsoup4配合使用,能够显著提升HTML内容的解析效果。
pip install beautifulsoup4 lxml
📜 代码示例
from bs4 import BeautifulSoup
import httpx
# Send an HTTP GET request to the specified URL using the httpx library
response = httpx.get("https://news.ycombinator.com/news")
# Save the content of the response
yc_web_page = response.content
# Use the BeautifulSoup library to parse the HTML content of the webpage
soup = BeautifulSoup(yc_web_page)
# Find all elements with the class "athing" (which represent articles on Hacker News) using the parsed HTML
articles = soup.find_all(class_="athing")
# Loop through each article and extract relevant data, such as the URL, title, and rank
for article in articles:
data = {
"URL": article.find(class_="titleline").find("a").get('href'), # Find the URL of the article by finding the first "a" tag within the element with class "titleline"
"title": article.find(class_="titleline").getText(), # Find the title of the article by getting the text content of the element with class "titleline"
"rank": article.find(class_="rank").getText().replace(".", "") # Find the rank of the article by getting the text content of the element with class "rank" and removing the period character
}
# Print the extracted data for the current article
print(data)
Mechanical Soup 是一个 Python 库,它提供了Requests和BeautifulSoup库的更高级别抽象。它通过将 Requests 的易用性与 Beautiful Soup 的 HTML 解析功能相结合,简化了 Web 抓取过程。
✨ 特征
👍 优点
👎 缺点
🤔 选择
Selenium, Playwright, Beautiful Soup
🔰 安装 Mechanical Soup
要安装 MechanicalSoup,请在终端或命令提示符中运行以下命令:
pip install MechanicalSoup
📜 代码示例
import mechanicalsoup
# Create a MechanicalSoup browser instance
browser = mechanicalsoup.StatefulBrowser()
# Perform a GET request to a webpage
browser.open("https://example.com")
# Extract data using BeautifulSoup methods
page_title = browser.get_current_page().title.text
print("Page Title:", page_title)
Selenium 是一种广泛使用的 Web 自动化工具,它允许开发人员以编程方式与 Web 浏览器交互。通常用于测试 Web 应用程序,但它也可以作为 Web 抓取的强大工具,尤其是在处理需要动态内容加载的 JavaScript 渲染的网站时。
✨ 特征
👍 优点
👎 缺点
🤔 选择
Playwright, Mechanical Soup, Crawlee, Scrapy
🔰 安装 Selenium
要安装 Selenium,请在终端或命令提示符中运行以下命令:
pip install selenium
📜 代码示例
from selenium import webdriver
# Setup the WebDriver (using Chrome in this example)
driver = webdriver.Chrome()
# Navigate to a web page
driver.get("https://example.com")
# Interact with the page (e.g., click a button)
button = driver.find_element_by_id("submit")
button.click()
# Extract data
content = driver.page_source
# Close the browser
driver.quit()
Playwright 是由 Microsoft 开发的现代 Web 自动化框架。它凭借单个API支持多个浏览器(包括Chromium、Firefox和WebKit),提供了与网页交互的强大功能。Playwright因其出色的速度、可靠性和处理复杂Web应用程序的能力,在测试和自动化领域备受青睐。与Selenium相似,在处理需要动态内容加载的网站时,Playwright也是一个强大的网络抓取工具。
✨ 特征
👍 优点
👎 缺点
🤔 选择
Selenium, Crawlee, Scrapy
🔰 安装 Playwright
要安装 Playwright,请在终端或命令提示符中运行以下命令:
pip install playwright
然后,您需要安装必要的浏览器二进制文件:
playwright install
📜 代码示例
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto("https://example.com")
# Interact with the page
page.click('button#submit')
# Extract data
content = page.content()
browser.close()
Scrapy是一个功能强大且高度灵活的Python框架,专门用于网络抓取。与常用于Web自动化的Selenium和Playwright不同,Scrapy的设计目标是以结构化和可扩展的方式从网站抓取大量数据。
✨ 特征
👍 优点
👎 缺点
🤔 选择
Crawlee, Beautiful Soup, Selenium, Playwright
🔰 安装 Scrapy
要安装 Scrapy,请在您的终端或命令提示符中运行以下命令:
pip install scrapy
📜 代码示例
import scrapy
class HackernewsSpiderSpider(scrapy.Spider):
name = 'hackernews_spider'
allowed_domains = ['news.ycombinator.com']
start_urls = ['http://news.ycombinator.com/']
def parse(self, response):
articles = response.css('tr.athing')
for article in articles:
yield {
"URL": article.css(".titleline a::attr(href)").get(),
"title": article.css(".titleline a::text").get(),
"rank": article.css(".rank::text").get().replace(".", "")
}
那么,在选择网络抓取项目的库时,您应该考虑哪些选项呢?以下表格总结了本文介绍的所有库的功能特性、主要用途、显著优点及潜在缺点:
图书馆 | 用例 | 易用性 | 特征 | 优点 | 缺点 | 选择 |
---|---|---|---|---|---|---|
Crawlee | 大规模抓取和浏览器自动化 | 简单 | 自动并行爬取、代理轮换、持久队列 | 易于设置、干净的代码、集成功能 | 新的有限教程 | Scrapy, Playwright, Beautiful Soup |
Requests | 发出 HTTP 请求 | 非常简单 | 简单的 API、SSL/TLS 支持、流媒体 | 大型社区,有据可查 | 没有异步,对于性能敏感型任务来说速度较慢 | httpx, urllib3, aiohttp |
HTTPX | 支持异步的 HTTP 请求 | 简单 | 异步支持、HTTP/2、可自定义传输 | 非阻塞请求,现代标准 | 学习强度更大,社区规模更小 | Requests, aiohttp, urllib3 |
Beautiful Soup | HTML/XML 解析 | 非常简单 | 树遍历、编码处理、多解析器支持 | 语法简单,非常适合初学者 | 可扩展性有限,不支持 JavaScript | lxml, html5lib |
Mechanical Soup | 表单处理、简单的网页抓取 | 简单 | 请求 + Beautiful Soup 集成,表单提交 | 简化的界面、会话处理 | 有限的高级功能 | Selenium, Playwright |
Selenium | 浏览器自动化、JavaScript 密集型网站 | 中等 | 跨浏览器的动态内容处理 | 模拟复杂的交互,多语言支持 | 速度较慢,资源密集 | Playwright, Crawlee, Scrapy |
Playwright | 高级浏览器自动化 | 中等 | 多浏览器支持、自动等待、并行执行 | 处理 JS 密集型网站、高级功能 | 学习强度更大,社区更小 | Selenium, Crawlee, Scrapy |
Scrapy | 大规模 Web 抓取 | 难 | 异步、分布式抓取、可扩展性 | 高效,处理复杂场景 | 学习强度更大,设置繁重 | Crawlee, Playwright, Selenium |
此处介绍的每种工具在专家抓取工具的工具包中都有其独特的用途。根据任务需求掌握它们的使用,将赋予您灵活选择最佳工具的能力,因此,在做出决定前,不妨大胆尝试每一种工具!
原文链接:https://blog.apify.com/what-are-the-best-python-web-scraping-libraries/