普通视图

发现新文章,点击刷新页面。
昨天以前首页

武装你的Python“工具箱”:盘点10个你必须熟练掌握的核心方法

作者 烛阴
2025年10月11日 22:47

一、字符串方法

字符串处理是我们日常编程中最高频的操作之一。

  1. .strip() - 去除首尾空白

    • 示例
      user_input = "  admin  \n"
      cleaned_input = user_input.strip()
      print(f"清理前: '{user_input}', 清理后: '{cleaned_input}'")
      # 输出: 
      #清理前: '  admin  
      #', 清理后: 'admin'
      
  2. .split() - 字符串切割

    • 示例
      csv_line = "apple,banana,orange,grape"
      fruits = csv_line.split(',')
      print(fruits)
      # 输出: ['apple', 'banana', 'orange', 'grape']
      
  3. .join() - 列表拼接成字符串

    • 示例
      words = ['Hello', 'Python', 'World']
      sentence = ' '.join(words)
      print(sentence)
      # 输出: Hello Python World
      
  4. f-string (格式化字符串)

    • 示例
      name = "张三"
      age = 30
      greeting = f"大家好,我叫{name},今年{age}岁了。"
      print(greeting)
      # 输出: 大家好,我叫张三,今年30岁了。
      

二、列表方法

列表是Python中使用最广泛的数据结构,下面这几个方法是管理列表内容的基础。

  1. .append() - 在末尾添加元素

    • 示例
      tasks = ['吃饭', '睡觉']
      tasks.append('写代码')
      print(tasks)
      # 输出: ['吃饭', '睡觉', '写代码']
      
  2. .sort() - 原地排序

    • 示例
      numbers = [3, 1, 4, 1, 5, 9, 2]
      numbers.sort(reverse=True) # reverse=True 表示降序
      print(numbers)
      # 输出: [9, 5, 4, 3, 2, 1, 1]
      

三、字典方法

字典通过键值对存储数据,访问速度极快。

  1. .get() - 安全地获取值

    • 示例
      user_info = {'name': 'Bob', 'age': 25}
      # 安全地获取职业,如果不存在,返回'未知'
      job = user_info.get('job', '未知')
      print(f"{user_info['name']}的职业是: {job}")
      # 输出: Bob的职业是: 未知
      
  2. .items() - 遍历键值对

    • 示例
      scores = {'数学': 95, '英语': 88, '科学': 92}
      for subject, score in scores.items():
          print(f"科目: {subject}, 分数: {score}")
      

四、通用内置函数

它们不属于某个特定类型,但功能强大,适用范围极广。

  1. len() - 获取长度

    • 示例
      print(len("Hello"))             # 5
      print(len([1, 2, 3, 4]))      # 4
      print(len({'a': 1, 'b': 2})) # 2
      
  2. range() - 生成数字序列

    • 示例
      # 打印 0 到 4
      for i in range(5):
          print(i, end=' ')
      # 输出: 0 1 2 3 4
      

结语

点个赞,关注我获取更多实用 Python 技术干货!如果觉得有用,记得收藏本文!

Python 数据抓取实战:从基础到反爬策略的完整指南

2025年10月10日 17:11

Python 数据抓取实战:从基础到反爬策略的完整指南

Meta Description(元描述):
本文系统讲解了 Python 数据抓取的完整流程,包括环境配置、核心库介绍、CSDN 博客实战案例、反爬机制应对、代理与 User-Agent 池的使用、以及数据抓取的合规性。适合数据分析师、开发者与电商从业者参考。

一、引言:数据抓取的价值与应用场景

在数字化时代,数据已成为驱动决策的核心资产
数据抓取作为获取网络公开数据的重要手段,广泛应用于 竞品分析、学术研究、商业智能、市场调研 等领域。

无论是爬取电商平台的商品价格、社交媒体的用户评论,还是技术社区的博客资源,掌握数据抓取技术都能帮助我们高效获取信息与分析趋势
本文将以 Python 为工具,通过实战案例演示数据抓取的完整流程,助力读者快速掌握可落地的技术方案。

二、数据抓取核心工具与环境准备

(一)核心库介绍

1. requests

简洁高效的 HTTP 请求库,支持处理复杂请求头、Cookie 管理等功能。
数据抓取的第一步,就是使用 requests 获取网页内容。

import requests

response = requests.get('https://www.baidu.com')
if response.status_code == 200:
    print(response.text)
else:
    print(f"请求失败,状态码: {response.status_code}")
2. BeautifulSoup

强大的 HTML 解析库,用于提取页面中的标签、属性和文本内容。

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
for link in links:
    print(link.get('href'))
3. lxml

高性能解析器,可与 BeautifulSoup 搭配使用以提升解析效率。

soup = BeautifulSoup(response.text, 'lxml')

(二)环境配置

  1. 安装依赖库:

    pip install requests beautifulsoup4 lxml
    

    若网络受限,可使用国内镜像:

    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests beautifulsoup4 lxml
    
  2. 浏览器调试工具:
    使用 Chrome 开发者工具(F12)分析网页结构,定位目标元素的标签与路径。
    右键点击 → “Copy → Copy selector”,即可快速获取 CSS 选择器,便于代码定位。

三、基础数据抓取流程:以 CSDN 博客为例

(一)目标分析

爬取关键词 “Python 爬虫” 的博客列表,提取:

  • 博客标题
  • 链接
  • 阅读量
  • 发布时间

这些信息能帮助我们了解相关主题在 CSDN 的热度与更新频率。

(二)分步实现

1. 发送 HTTP 请求
import requests

url = 'https://so.csdn.net/so/search/s.do?q=Python爬虫&t=blog'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers)
2. 解析 HTML 页面
from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, 'lxml')
blog_items = soup.select('.search-list .blog-list-box')
3. 提取目标数据
data = []
for item in blog_items:
    title = item.select_one('.title').get_text().strip()
    link = item.select_one('.title a')['href']
    read_count = item.select_one('.read-num')
    read_count = read_count.get_text().strip() if read_count else '未知'
    publish_time = item.select_one('.time').get_text().strip()
    
    data.append({
        '标题': title,
        '链接': link,
        '阅读量': read_count,
        '发布时间': publish_time
    })
4. 保存数据为 CSV 文件
import pandas as pd

df = pd.DataFrame(data)
df.to_csv('csdn_python_crawler_blogs.csv', index=False, encoding='utf-8-sig')

四、高级技巧与反爬虫应对

(一)分页数据抓取

使用循环与随机延迟遍历多页数据,模拟人类行为:

import time, random
for page in range(1, 6):
    url = f'https://so.csdn.net/so/search/s.do?q=Python爬虫&t=blog&p={page}'
    response = requests.get(url, headers=headers)
    time.sleep(random.uniform(1, 2))

(二)动态页面处理(Selenium)

from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome()
driver.get('https://example.com/dynamic_page')
time.sleep(3)
html = driver.page_source
driver.quit()
soup = BeautifulSoup(html, 'lxml')

(三)代理 IP 与 User-Agent 池

from fake_useragent import UserAgent
ua = UserAgent()
headers = {'User-Agent': ua.random}

proxies = {
    'http': 'http://your_proxy_ip:port',
    'https': 'https://your_proxy_ip:port'
}

response = requests.get('https://example.com', headers=headers, proxies=proxies)

五、实战案例:电商商品信息抓取

目标:抓取电商平台的手机商品数据,包括名称、价格、评价数。
关键步骤包括:

  • 页面结构分析
  • 设置反爬头信息
  • 延迟与代理 IP
  • 数据清洗与格式化

例如使用正则提取价格数值:

import re
price_str = "¥1999"
price_num = float(re.search(r'\d+', price_str).group())

六、合规与伦理:数据抓取的边界

(一)遵守 robots 协议

示例:

from urllib.robotparser import RobotFileParser

rp = RobotFileParser()
rp.set_url('https://example.com/robots.txt')
rp.read()
rp.can_fetch('*', 'https://example.com/some_page.html')

(二)控制请求频率

避免高频访问,添加 1–3 秒随机延迟:

time.sleep(random.uniform(1, 3))

(三)数据合法使用

仅用于合法用途,不涉及隐私、商业欺诈或版权内容。遵守 GDPR、《网络安全法》等隐私保护规范。

七、总结与拓展

(一)核心价值

本文从 基础抓取 → 实战演示 → 反爬策略 → 合规使用 全面展示了数据抓取的实用体系。

(二)进阶方向

  • 使用 Scrapy 实现分布式抓取
  • 利用 aiohttp 进行异步请求提升效率
  • 使用 MySQL / MongoDB 存储结构化与非结构化数据

(三)实践建议

从静态网页入门,逐步挑战动态与登录验证场景,持续关注反爬变化。

推荐阅读:

HelloGitHub 第 114 期

2025年9月28日 07:49
本期共有 39 个项目,包含 C 项目 (2),C# 项目 (2),C++ 项目 (3),Go 项目 (4),Java 项目 (2),JavaScript 项目 (5),Kotlin 项目 (1),Python 项目 (5),Rust 项目 (3),Swift 项目 (2),人工智能 (4),其它 (5),开源书籍 (1)
❌
❌