
區塊鏈API推薦,快速開發去中心化應用
使用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/