爬虫01 - 爬虫原理及其入门
一:爬虫原理
学习爬虫之前前置知识需要了解这些:
所谓爬虫,就是通过模拟浏览器行为向目标网站发送请求(HTTP/HTTPS),解析响应内容并提取所需数据,最终存储到本地或数据库
- 请求数据(构造HTTP请求(GET/POST)获取网页内容)
- 解析数据(通过正则表达式、XPath或解析库(如BeautifulSoup)提取目标信息)
- 存储数据(将结果保存为CSV、Excel或数据库(如MySQL、MongoDB)
1:爬虫的优势
- 丰富的库支持:Requests(HTTP请求)、BeautifulSoup/Scrapy(解析)、Selenium(动态渲染)等库简化开发流程。
- 语法简洁高效:Python代码可读性强,适合快速实现复杂逻辑。
- 生态成熟:社区活跃,反爬解决方案和开源项目资源丰富。
2:爬虫的核心库
pip install requests
pip install beautifulsoup4 # 注意这个是4版本的
pip install selenium
pip install scrapy
3:经典举例
举一个简单的top250首页电影的评分和电影名
import requests
from bs4 import BeautifulSoup
# 1:构建请求,通过request先获取到对应的HTML/XML
url = "https://movie.douban.com/top250"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
# 准备使用bs4进行解析,下面将使用find, find_all进行解析
soup = BeautifulSoup(response.text, "html.parser")
movies = []
# 对于找到的所有的item进行解析
for item in soup.find_all("div", class_="item"):
title = item.find("span", class_="title").text
rating = item.find("span", class_="rating_num").text
movies.append({"title": title, "rating": rating})
for index, movie in enumerate(movies):
print(f"{index + 1}. {movie['title']} - {movie['rating']}")