什么是网络爬虫?
网络爬虫(Web Crawler)是自动抓取网页信息的程序。Python是最常用的爬虫语言之一。
必备库安装
pip install requests beautifulsoup4 lxml
基础用法
发送HTTP请求
import requests
# GET请求
response = requests.get('https://api.github.com')
print(response.status_code) # 200
# 带参数
response = requests.get('https://httpbin.org/get', params={'key': 'value'})
# POST请求
response = requests.post('https://httpbin.org/post', data={'name': '小明'})
# 设置Headers
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
response = requests.get('https://example.com', headers=headers)
解析HTML
from bs4 import BeautifulSoup
html = '<div class="article"><h2>标题</h2><p>内容</p></div>'
soup = BeautifulSoup(html, 'html.parser')
# 查找元素
h2 = soup.find('h2')
print(h2.text) # 标题
# 查找所有链接
links = soup.find_all('a')
# CSS选择器
items = soup.select('.article')
注意事项
- 遵守robots.txt协议
- 控制请求频率,不要频繁访问
- 设置User-Agent模拟浏览器
- 不要爬取个人隐私和版权内容
总结
爬虫是获取数据的强大工具,但一定要合法合规使用。掌握requests和BeautifulSoup,你已经能爬取大部分网站了。