程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python3爬虫教程与示例代码(python爬虫基本代码)

hfteth 2025-04-06 16:18:32 技术文章 6 ℃

以下是 Python3 编写网络爬虫的简明教程,包含基础步骤和示例代码:


一、常用工具库

  1. 请求库

O requests:简单易用的 HTTP 请求库

O aiohttp:异步 HTTP 客户端(适合高性能爬虫)

  1. 解析库

O BeautifulSoup:HTML/XML 解析库

O lxml:支持 XPath 的高性能解析库

O parsel:Scrapy 内置的选择器库

  1. 框架

O Scrapy:专业的爬虫框架

O Selenium:浏览器自动化工具(应对动态网页)


二、基础爬虫示例

示例1:使用 requests + BeautifulSoup

python

import requests

from bs4 import BeautifulSoup


# 1. 发送请求

url = 'https://example.com'

headers = {'User-Agent': 'Mozilla/5.0'} # 模拟浏览器头

response = requests.get(url, headers=headers)

response.encoding = 'utf-8' # 设置编码


# 2. 解析内容

soup = BeautifulSoup(response.text, 'html.parser')

title = soup.find('h1').text # 获取标题

links = [a['href'] for a in soup.find_all('a')] # 获取所有链接


# 3. 保存结果

with open('output.txt', 'w') as f:

f.write(f"标题: {title}\n链接: {', '.join(links)}")

示例2:使用 XPath 解析(lxml)

python

from lxml import etree

import requests

url = 'https://example.com'

html = requests.get(url).text

tree = etree.HTML(html)

# 使用XPath提取数据

results = tree.xpath('//div[@class="content"]/text()')

print(results)


三、高级技巧

  1. 处理动态内容

python

from selenium import webdriver

driver = webdriver.Chrome()

driver.get('https://dynamic-site.com')

dynamic_content = driver.find_element_by_class_name('data').text

driver.quit()

  1. 应对反爬措施

O 使用代理IP:

python

proxies = {'http': 'http://10.10.1.10:3128'}

requests.get(url, proxies=proxies)

O 随机请求头:使用 fake_useragent 库生成

O 设置请求延迟:time.sleep(random.uniform(1,3))

  1. 异步爬虫

python

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()


urls = ['https://site1.com', 'https://site2.com']

tasks = [fetch(url) for url in urls]

results = asyncio.run(asyncio.gather(*tasks))


四、注意事项

  1. 遵守规则

O 检查网站的 robots.txt(如:
https://example.com/robots.txt)

O 尊重网站设定的 Crawl-delay

  1. 异常处理

python

try:

response = requests.get(url, timeout=5)

response.raise_for_status() # 检查HTTP错误

except requests.exceptions.RequestException as e:

print(f"请求失败: {e}")

  1. 数据存储

O 文件:CSV、JSON

O 数据库:MySQL、MongoDB

O 云存储:AWS S3


五、推荐学习路径

  1. 掌握 HTTP 协议基础
  2. 学习 HTML 结构/XPath 语法
  3. 熟悉常见反爬机制及应对策略
  4. 了解数据库存储基础
  5. 学习分布式爬虫设计(Scrapy-Redis)

建议从简单静态页面开始练习,逐步过渡到复杂项目。可使用官方文档(如 Scrapy 文档)作为参考。

最近发表
标签列表