“天啊!原来用Python抓数据这么简单?” 这是很多新手在接触爬虫后的真实反应!今天咱们就来揭开网页爬虫的神秘面纱(手把手教学版),教你用最基础的Python语法实现数据抓取。(文末有超实用的反爬虫应对技巧,别错过!)
简单来说,爬虫就是个自动化数据收集器!想象你每天手动打开网页复制粘贴数据——现在有个机器人帮你24小时自动完成这些操作,这就是爬虫的魔力!
robots.txt
文件(在网站域名后加/robots.txt就能看到)pip install requests beautifulsoup4
(别问为什么用这两个库,问就是:简单!强大!够用!)
新建spider.py
文件,然后…(直接往下看代码)
import requests
url = 'https://movie.douban.com/top250'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)
print(response.text) # 看到网页源码了吗?!
(注意:这里必须添加User-Agent,不然会被识别为机器人!)
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# 抓取所有电影标题
titles = soup.find_all('span', class_='title')
for title in titles:
print(title.get_text())
with open('douban_movies.txt', 'w', encoding='utf-8') as f:
for title in titles:
f.write(title.get_text() + '\n')
(恭喜!你现在已经拥有自己的电影数据库了!)
response.encoding = 'utf-8' # 强制设置编码
# 或者
response.encoding = response.apparent_encoding
上大招——Selenium!(模拟浏览器操作)
from selenium import webdriver
driver = webdriver.Chrome()
driver.get(url)
page_source = driver.page_source
# 后续解析步骤同上
headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)',
'Referer': 'https://www.google.com/',
'Cookie': '你的cookie'
}
for page in range(0, 250, 25):
url = f'https://movie.douban.com/top250?start={page}'
# 重复抓取步骤...
用正则表达式处理复杂文本:
import re
price = re.search(r'\d+\.\d+', '售价:128.5元').group()
(附赠学习资源:W3School + 官方文档 + Chrome开发者工具)
刚开始学爬虫时,你可能会有100次想砸键盘的冲动!但坚持下来就会发现:那些看似复杂的验证码、加密参数,不过是披着狼皮的羊。记住每个高手都是从菜鸟过来的,多实战才是王道!
下次教你们怎么用Scrapy搭建分布式爬虫(这个更刺激!),想学的评论区举个手?