先锋AV资源-先锋AV资源福利网-先锋AV资源网-先锋av资源在线-先锋AV资源在线美女-先锋av资源站-先锋av资源站你懂-先锋b怡红院-先锋va资源站-先锋vα资源

Python網(wǎng)絡(luò)爬蟲(chóng)實(shí)戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

首頁(yè) > 產(chǎn)品大全 > Python網(wǎng)絡(luò)爬蟲(chóng)實(shí)戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

Python網(wǎng)絡(luò)爬蟲(chóng)實(shí)戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

Python網(wǎng)絡(luò)爬蟲(chóng)實(shí)戰(zhàn) Scrapy與Beautiful Soup的使用及數(shù)據(jù)處理技巧

網(wǎng)絡(luò)爬蟲(chóng)是獲取互聯(lián)網(wǎng)數(shù)據(jù)的重要工具,Python因其豐富的庫(kù)和簡(jiǎn)潔的語(yǔ)法成為爬蟲(chóng)開(kāi)發(fā)的首選語(yǔ)言。在眾多爬蟲(chóng)工具中,Scrapy和Beautiful Soup各具特色,結(jié)合使用能高效完成數(shù)據(jù)采集與處理任務(wù)。

一、Scrapy框架的使用

Scrapy是一個(gè)功能強(qiáng)大的爬蟲(chóng)框架,適合大規(guī)模、結(jié)構(gòu)化的數(shù)據(jù)采集。

1. 基礎(chǔ)架構(gòu)

  • 引擎(Engine):控制數(shù)據(jù)流,協(xié)調(diào)各組件工作
  • 調(diào)度器(Scheduler):管理請(qǐng)求隊(duì)列
  • 下載器(Downloader):獲取網(wǎng)頁(yè)內(nèi)容
  • 爬蟲(chóng)(Spider):定義爬取邏輯和數(shù)據(jù)提取規(guī)則
  • 項(xiàng)目管道(Pipeline):處理提取的數(shù)據(jù)

2. 快速入門

`python import scrapy

class ExampleSpider(scrapy.Spider):
name = 'example'
start_urls = ['http://example.com']

def parse(self, response):
# 提取數(shù)據(jù)

title = response.css('h1::text').get()
yield {'title': title}

# 跟進(jìn)鏈接

for link in response.css('a::attr(href)').getall():
yield response.follow(link, self.parse)
`

3. 高級(jí)特性

  • 中間件:自定義請(qǐng)求/響應(yīng)處理
  • Item Loader:結(jié)構(gòu)化數(shù)據(jù)提取
  • Feed導(dǎo)出:支持JSON、CSV等多種格式
  • 去重過(guò)濾:自動(dòng)避免重復(fù)爬取

二、Beautiful Soup的使用

Beautiful Soup是靈活的HTML/XML解析庫(kù),適合小規(guī)模或結(jié)構(gòu)不規(guī)則的頁(yè)面。

1. 基礎(chǔ)解析

`python from bs4 import BeautifulSoup import requests

html = requests.get('http://example.com').text
soup = BeautifulSoup(html, 'lxml')

多種選擇器

soup.find('div', class='content')
soup.select('div.content > p')
soup.find
all(text='特定文本')
`

2. 解析器選擇

  • lxml:速度快,容錯(cuò)性好(推薦)
  • html.parser:Python內(nèi)置,無(wú)需額外安裝
  • html5lib:容錯(cuò)性最好,速度較慢

三、數(shù)據(jù)處理技巧

1. 數(shù)據(jù)清洗

`python import re from datetime import datetime

去除空白字符

def clean_text(text):
return re.sub(r'\s+', ' ', text).strip()

日期標(biāo)準(zhǔn)化

def normalizedate(datestr):
formats = ['%Y-%m-%d', '%d/%m/%Y', '%b %d, %Y']
for fmt in formats:
try:
return datetime.strptime(date_str, fmt).date()
except:
continue
return None
`

2. 數(shù)據(jù)驗(yàn)證

`python import pandas as pd from cerberus import Validator

schema = {
'title': {'type': 'string', 'required': True},
'price': {'type': 'float', 'min': 0},
'url': {'type': 'string', 'regex': '^https?://'}
}

validator = Validator(schema)
if validator.validate(data):
# 數(shù)據(jù)有效

pass
`

3. 數(shù)據(jù)存儲(chǔ)

`python # 存儲(chǔ)到CSV

import csv
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data_list)

存儲(chǔ)到數(shù)據(jù)庫(kù)

import sqlite3
conn = sqlite3.connect('data.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS items
(title TEXT, price REAL, url TEXT)''')
`

四、數(shù)據(jù)處理服務(wù)設(shè)計(jì)

1. 服務(wù)架構(gòu)

數(shù)據(jù)采集層(Scrapy/Requests) → 數(shù)據(jù)解析層(Beautiful Soup) →
數(shù)據(jù)處理層(清洗/驗(yàn)證) → 數(shù)據(jù)存儲(chǔ)層(數(shù)據(jù)庫(kù)/文件) →
數(shù)據(jù)API層(RESTful接口)

2. 錯(cuò)誤處理機(jī)制

  • 網(wǎng)絡(luò)請(qǐng)求重試
  • 解析失敗日志記錄
  • 數(shù)據(jù)質(zhì)量監(jiān)控
  • 異常數(shù)據(jù)隔離

3. 性能優(yōu)化

`python # 使用aiohttp異步請(qǐng)求

import aiohttp
import asyncio

async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()

使用線程池

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(maxworkers=10) as executor:
results = executor.map(process
data, data_list)
`

五、最佳實(shí)踐建議

  1. 遵守robots.txt:尊重網(wǎng)站爬取規(guī)則
  2. 設(shè)置合理延遲:避免對(duì)目標(biāo)網(wǎng)站造成壓力
  3. 使用User-Agent:模擬真實(shí)瀏覽器訪問(wèn)
  4. 處理反爬機(jī)制:合理使用代理IP和Cookie
  5. 數(shù)據(jù)去重:避免存儲(chǔ)重復(fù)數(shù)據(jù)
  6. 定期維護(hù):更新選擇器,適應(yīng)網(wǎng)站改版

六、完整示例:電商價(jià)格監(jiān)控系統(tǒng)

`python import scrapy from bs4 import BeautifulSoup import pandas as pd from datetime import datetime

class PriceMonitorSpider(scrapy.Spider):
name = 'pricemonitor'

def start
requests(self):
urls = ['http://example.com/products']
for url in urls:
yield scrapy.Request(url, callback=self.parselist)

def parse
list(self, response):
soup = BeautifulSoup(response.text, 'lxml')
products = soup.select('.product-item')

for product in products:
item = {
'name': product.selectone('.name').text.strip(),
'price': float(product.select
one('.price').text.replace('¥', '')),
'url': response.urljoin(product.selectone('a')['href']),
'crawl
time': datetime.now().isoformat()
}
yield item

# 在settings.py中配置數(shù)據(jù)管道

ITEM_PIPELINES = {

'project.pipelines.DataCleanPipeline': 300,

'project.pipelines.DatabasePipeline': 800,

}

`

七、

Scrapy和Beautiful Soup是Python爬蟲(chóng)生態(tài)中的黃金組合。Scrapy適合構(gòu)建完整的爬蟲(chóng)項(xiàng)目,提供完整的框架支持;Beautiful Soup則在小規(guī)模、快速開(kāi)發(fā)的場(chǎng)景中表現(xiàn)出色。結(jié)合兩者的優(yōu)勢(shì),配合合理的數(shù)據(jù)處理流程,可以構(gòu)建出高效、穩(wěn)定的數(shù)據(jù)采集與處理服務(wù)。

在實(shí)際開(kāi)發(fā)中,應(yīng)根據(jù)具體需求選擇合適工具,注重代碼的可維護(hù)性和擴(kuò)展性,同時(shí)遵守相關(guān)法律法規(guī)和網(wǎng)站使用條款,實(shí)現(xiàn)可持續(xù)的數(shù)據(jù)采集服務(wù)。

如若轉(zhuǎn)載,請(qǐng)注明出處:http://m.91xlb.cn/product/25.html

更新時(shí)間:2026-08-04 19:43:35

主站蜘蛛池模板: 免费在线成人网站 | 免费欧美肏屄大片 | 精品视频六区 | 欧美男同网站 | 日韩一级黄色电影 | 91干逼国产精品 | 超碰肏逼 | 中文字幕第一页 | 激情五月天婷婷 | 日韩电影在线 | 日韩欧美理论 | 西瓜影院在线观看 | 能播放的毛片网 | 男的爱看的黄网址 | 性爱福利视频网 | 成人肉漫在线观看 | 日本中文在线字幕 | 91网址视频| 内射合集对白在线 | 国产一级免费大片 | 四虎婷婷 | 国产传媒视频 | 国内自产拍自拍 | 亚洲人成免费网站 | 爆乳少妇AV | 日韩伦理片网站 | 精品视频91 | 欧美日韩二三区 | 日韩成人影片 | 午夜伦不卡| 伦理在线电影 | 欧美另类口爆 | 午夜鲁丝无码视频 | 国产精品电影久 | 成人一二三区亚洲 | 日韩精品久爱 | 国产午夜电影 | 国产在线奶奶色 | 岛国大片在线播放 | 黄色三级片网址 | 午夜网站网址大全 |