爬取数据需先用requests获取网页内容,再用BeautifulSoup解析HTML提取信息,动态内容使用Selenium模拟浏览器,最后清洗并保存为CSV、JSON或数据库。

爬取数据是Python中常见的任务,主要通过发送HTTP请求获取网页内容,再解析出需要的信息。实现这一过程通常使用几个核心库:requests、BeautifulSoup、re(正则)、lxml,有时也会用到Selenium处理动态页面。
使用 requests 库可以轻松获取网页的HTML源码。
示例:import requests
<p>url = '<a href="https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635">https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635</a>'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)</p><p>if response.status_code == 200:
html = response.text
else:
print("请求失败,状态码:", response.status_code)
注意添加 User-Agent 防止被反爬机制拦截。部分网站会验证请求头。
常用 BeautifulSoup 解析HTML结构,结合CSS选择器或标签名提取内容。
立即学习“Python免费学习笔记(深入)”;
示例:from bs4 import BeautifulSoup
<p>soup = BeautifulSoup(html, 'html.parser')
titles = soup.find<em>all('h2', class</em>='title') # 查找所有class为title的h2标签</p><p>for title in titles:
print(title.get_text(strip=True))
也可以用 select() 方法使用CSS选择器:
soup.select('div.content p') 获取 div.content 下的所有 p 标签。
如果网页内容由JavaScript动态生成,requests 拿不到真实数据,需使用 Selenium 或 Playwright。
示例(Selenium):from selenium import webdriver
from selenium.webdriver.common.by import By
<p>driver = webdriver.Chrome()
driver.get('<a href="https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635">https://www.php.cn/link/b05edd78c294dcf6d960190bf5bde635</a>')</p><h1>等待元素加载(可配合 WebDriverWait)</h1><p>elements = driver.find_elements(By.CLASS_NAME, 'item')
for elem in elements:
print(elem.text)</p><p>driver.quit()
这种方式模拟真实浏览器操作,适合抓取SPA(单页应用)或需要登录、点击翻页的场景。
提取后的数据常需清洗,可用 re、pandas 等工具处理。
保存方式包括:
import csv 或 pandas.DataFrame.to_csv()
json.dump(data, open('data.json', 'w', encoding='utf-8'))
基本上就这些。掌握 requests + BeautifulSoup 能解决大多数静态页面需求。遇到反爬时考虑加 headers、延时、代理 IP。动态内容上 Selenium。不复杂但容易忽略细节,比如编码、网络超时、频率控制。
以上就是如何用python爬取数据的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号