本文目录导读:

Python 基础方法
使用 requests + BeautifulSoup
import requests
from bs4 import BeautifulSoup
# 发送请求
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
url = 'https://example.com'
response = requests.get(url, headers=headers)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 提取数据= soup.find('h1').text
links = soup.find_all('a')
for link in links:
print(link.get('href'), link.text)
处理动态内容
使用 Selenium(处理JavaScript渲染)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
# 配置无头浏览器
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
# 加载页面
driver.get('https://example.com')
# 等待加载
driver.implicitly_wait(10)
# 获取渲染后的内容
content = driver.page_source
element = driver.find_element(By.CLASS_NAME, 'target-class')
text = element.text
driver.quit()
使用 Scrapy 框架(适合大规模抓取)
import scrapy
class MySpider(scrapy.Spider):
name = 'example_spider'
start_urls = ['https://example.com']
def parse(self, response):
# 提取数据
yield {
'title': response.css('h1::text').get(),
'links': response.css('a::attr(href)').getall(),
}
# 翻页
next_page = response.css('a.next::attr(href)').get()
if next_page:
yield response.follow(next_page, self.parse)
命令行工具
curl 命令
# 基本用法 curl https://example.com # 添加请求头 curl -H "User-Agent: Mozilla/5.0" https://example.com # 保存到文件 curl -o output.html https://example.com
wget 命令
# 下载网页 wget https://example.com # 递归下载 wget -r -l 2 https://example.com
Node.js 方法
const axios = require('axios');
const cheerio = require('cheerio');
async function scrapePage() {
const response = await axios.get('https://example.com');
const $ = cheerio.load(response.data);
// 提取数据
const title = $('h1').text();
const links = [];
$('a').each((i, el) => {
links.push({
text: $(el).text(),
href: $(el).attr('href')
});
});
return { title, links };
}
高级技巧
反爬虫处理
# 使用代理
proxies = {
'http': 'http://proxy.example.com:8080',
'https': 'https://proxy.example.com:8080'
}
response = requests.get(url, proxies=proxies)
# 随机User-Agent
import random
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
]
headers = {'User-Agent': random.choice(user_agents)}
# 处理验证码(使用打码平台)
import ddddocr
ocr = ddddocr.DdddOcr()
with open('captcha.png', 'rb') as f:
result = ocr.classification(f.read())
异步抓取(提高效率)
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = ['https://example.com/page1', 'https://example.com/page2']
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
responses = await asyncio.gather(*tasks)
注意事项
- 遵守 robots.txt:检查网站的爬取规则
- 设置请求间隔:避免对服务器造成压力
- 处理异常:网络错误、元素不存在等
- 数据存储:考虑使用数据库或CSV文件
- 法律合规:确保抓取行为合法
推荐工具选择
- 简单抓取:requests + BeautifulSoup
- 动态页面:Selenium 或 Playwright
- 大规模抓取:Scrapy 框架
- API接口:直接使用 requests 调用API
根据你的具体需求选择合适的方法,如果需要更详细的某个方法说明,可以告诉我!