Python使用Scrapling進行網(wǎng)頁采集的用法詳解
Scrapling 是一個 Python Web Scraping 框架,可以用來抓取靜態(tài)網(wǎng)頁、動態(tài) 網(wǎng)頁,也可以編寫多頁面爬蟲。它的 API 風格有點像 requests + BeautifulSoup + Scrapy + Playwright 的結合體。
項目地址:D4Vinci/Scrapling
官方文檔:Scrapling Docs
適合什么場景
Scrapling 主要適合這些任務:
- 抓取普通 HTML 頁面
- 使用 CSS / XPath 提取網(wǎng)頁內容
- 抓取 JavaScript 渲染后的頁面
- 編寫多頁面爬蟲
- 處理分頁、詳情頁、表格、商品列表等結構化數(shù)據(jù)
- 使用瀏覽器模式處理更復雜的網(wǎng)站
簡單來說:
普通網(wǎng)頁:Fetcher 動態(tài) 網(wǎng)頁:DynamicFetcher 復雜保護頁面:StealthyFetcher 多頁面爬蟲:Spider
安裝
Scrapling 要求 Python 3.10+。
基礎安裝:
pip install scrapling
如果需要抓取 JavaScript 渲染頁面,需要安裝 fetchers 依賴:
pip install "scrapling[fetchers]" scrapling install
Demo 1:抓取普通網(wǎng)頁
from scrapling.fetchers import Fetcher
page = Fetcher.get("https://quotes.toscrape.com/")
for quote in page.css(".quote"):
text = quote.css(".text::text").get()
author = quote.css(".author::text").get()
print({
"text": text,
"author": author,
})
這里的選擇器和 Scrapy 很像:
page.css("h1::text").get()
page.css("a::attr(href)").getall()
page.xpath("http://h1/text()").get()
Demo 2:抓取分頁
from scrapling.fetchers import Fetcher
url = "https://quotes.toscrape.com/"
while url:
page = Fetcher.get(url)
for quote in page.css(".quote"):
print({
"text": quote.css(".text::text").get(),
"author": quote.css(".author::text").get(),
})
next_href = page.css(".next a::attr(href)").get()
url = page.urljoin(next_href) if next_href else None
page.urljoin() 可以把相對鏈接轉換成完整 URL。
Demo 3:抓取商品列表
from scrapling.fetchers import Fetcher
page = Fetcher.get("https://books.toscrape.com/")
books = []
for item in page.css("article.product_pod"):
books.append({
"title": item.css("h3 a::attr(title)").get(),
"price": item.css(".price_color::text").get(),
"stock": item.css(".availability::text").getall()[-1].strip(),
"url": page.urljoin(item.css("h3 a::attr(href)").get()),
})
print(books)
Demo 4:用文本和正則查找元素
from scrapling.fetchers import Fetcher
page = Fetcher.get("https://books.toscrape.com/index.html")
book = page.find_by_text("Tipping the Velvet")
print(book.text)
print(page.urljoin(book.attrib["href"]))
price = page.find_by_regex(r"£[\d\.]+")
print(price.text)
這類 API 適合快速定位頁面里的文字內容,不一定每次都要手寫復雜 CSS 選擇器。
Demo 5:抓取 JavaScript 動態(tài)頁面
from scrapling.fetchers import DynamicFetcher
page = DynamicFetcher.fetch(
"https://quotes.toscrape.com/js/",
headless=True,
network_idle=True,
)
for quote in page.css(".quote"):
print({
"text": quote.css(".text::text").get(),
"author": quote.css(".author::text").get(),
})
如果頁面內容是前端 JS 渲染出來的,普通 Fetcher 可能抓不到,這時可以使用 DynamicFetcher。
Demo 6:等待元素出現(xiàn)
from scrapling.fetchers import DynamicFetcher
page = DynamicFetcher.fetch(
"https://quotes.toscrape.com/js-delayed/",
headless=True,
wait_selector=".quote",
wait_selector_state="visible",
)
quotes = page.css(".quote .text::text").getall()
print(quotes)
這個寫法適合頁面加載較慢、需要等待某個元素出現(xiàn)的情況。
Demo 7:寫一個 Spider
如果要做正式爬蟲,推薦用 Spider。
from scrapling.spiders import Spider, Response
class QuotesSpider(Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com/"]
concurrent_requests = 5
async def parse(self, response: Response):
for quote in response.css(".quote"):
yield {
"text": quote.css(".text::text").get(""),
"author": quote.css(".author::text").get(""),
"tags": quote.css(".tag::text").getall(),
}
next_page = response.css(".next a::attr(href)").get()
if next_page:
yield response.follow(next_page, callback=self.parse)
result = QuotesSpider().start()
print(f"抓到 {len(result.items)} 條")
result.items.to_json("quotes.json")
Spider 的結構比較清晰:
name:爬蟲名稱 start_urls:起始頁面 parse:解析響應,yield 數(shù)據(jù)或新請求 response.follow:繼續(xù)跟進下一頁
Fetcher、DynamicFetcher、Spider 怎么選
| 場景 | 推薦 |
|---|---|
| 普通 HTML 頁面 | Fetcher |
| 需要 cookie / session | FetcherSession |
| JS 渲染頁面 | DynamicFetcher |
| 需要瀏覽器操作 | DynamicFetcher + page_action |
| 多頁面爬蟲 | Spider |
| 更復雜的反爬頁面 | StealthyFetcher |
小結
Scrapling 的優(yōu)點是 API 比較統(tǒng)一:無論是普通請求、動態(tài)頁面,還是 Spider 爬蟲,最終拿到的頁面對象都可以用類似的方式解析:
page.css(...) page.xpath(...) page.find_by_text(...) page.find_by_regex(...)
如果你之前用過 requests、BeautifulSoup、Scrapy 或 Playwright,Scrapling 上手會比較快。
它適合從小腳本逐步升級到正式爬蟲項目:一開始可以用 Fetcher.get() 寫簡單 demo,后面再改成 Spider 做分頁、并發(fā)和數(shù)據(jù)導出。
注意事項
使用 Scrapling 抓取網(wǎng)站時,需要遵守目標網(wǎng)站的服務條款、robots.txt 和相關法律法規(guī)。建議優(yōu)先抓取公開、允許訪問的數(shù)據(jù),并控制請求頻率,避免對目標網(wǎng)站造成壓力。
以上就是Python使用Scrapling進行網(wǎng)頁采集的用法詳解的詳細內容,更多關于Python Scrapling網(wǎng)頁采集的資料請關注腳本之家其它相關文章!
相關文章
python使用openpyxl庫修改excel表格數(shù)據(jù)方法
今天小編就為大家分享一篇python使用openpyxl庫修改excel表格數(shù)據(jù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Python圖像處理庫PIL的ImageDraw模塊介紹詳解
這篇文章主要介紹了Python圖像處理庫PIL的ImageDraw模塊介紹詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
pytorch DataLoader的num_workers參數(shù)與設置大小詳解
這篇文章主要介紹了pytorch DataLoader的num_workers參數(shù)與設置大小詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05

