【爬虫】- 爬虫原理及其入门

爬虫01 - 爬虫原理及其入门

文章目录

一:爬虫原理

学习爬虫之前前置知识需要了解这些:

我的HTTP介绍, 了解如何调用,requests需要

我的html介绍, 了解html结构

我的css介绍,了解选择器部分, 因为要用bs4选择对应位置的内容
所谓爬虫,就是通过模拟浏览器行为向目标网站发送请求(HTTP/HTTPS),解析响应内容并提取所需数据,最终存储到本地或数据库

  1. 请求数据(构造HTTP请求(GET/POST)获取网页内容)
  2. 解析数据(通过正则表达式、XPath或解析库(如BeautifulSoup)提取目标信息)
  3. 存储数据(将结果保存为CSV、Excel或数据库(如MySQL、MongoDB)

1:爬虫的优势‌

  • 丰富的库支持‌:Requests(HTTP请求)、BeautifulSoup/Scrapy(解析)、Selenium(动态渲染)等库简化开发流程。
  • ‌语法简洁高效‌:Python代码可读性强,适合快速实现复杂逻辑。
  • ‌生态成熟‌:社区活跃,反爬解决方案和开源项目资源丰富。

2:爬虫的核心库

shell 复制代码
pip install requests
pip install beautifulsoup4 # 注意这个是4版本的
pip install selenium
pip install scrapy

3:经典举例

举一个简单的top250首页电影的评分和电影名

python 复制代码
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']}")

4:合规问题

相关推荐
wuyk55515 小时前
Spider-第20讲-综合实战可上线爬虫
大数据·爬虫·python·elasticsearch
wuyk5552 天前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
wuyk5554 天前
Spider-第14讲-表单提交与CSRF
前端·爬虫·python·elasticsearch·csrf
wuyk5556 天前
Spider-第11讲-工程化改造与可维护性
大数据·爬虫·elasticsearch·搜索引擎
wuyk5556 天前
Spider-第12讲-asyncio异步并发爬取
大数据·爬虫·elasticsearch·搜索引擎
小宋10216 天前
AI 爬虫把大学图书馆站点拖垮:按行为指纹给爬虫分类、按类发配额、用边缘缓存分层,以带宽成本结构和真实用户 P95 延迟定档
人工智能·爬虫·分类
wuyk5557 天前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
wuyk5557 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
wuyk5558 天前
Spider-第07讲-JSON接口与正则提取
爬虫·python·json
feasibility.8 天前
一物降一物?AI逆向没有终局:REA拆App,BLA设套,LASIK清场
人工智能·爬虫·github·逆向·skill·rea