Python之爬虫

目录

HTTP请求

HTTP:HypertextTransferProtcol 超文本传输协议

1、请求行

python 复制代码
POST/user/info?new_user=true HTTP/1.1

#资源了路径user/info 查询参数new_user=true 协议版本HTTP/1.1

2、请求头

python 复制代码
Host:www.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; ×64)

#host指主机域名

python 复制代码
User-Agent:curl/7.77.0

#告知服务器客户端的相关信息

python 复制代码
Accept:*/*

#客户端想接受的响应数据是什么类型

3、请求体

python 复制代码
{"username":"刘威","email":"liuwei@hotmail.com"}

HTTP响应

python 复制代码
# 状态行
HTTP/1.1 200 OK
# 响应头
Date:Fri,27Jan 2023 02:10:50 GMT
Content-Type:text/html;charset=utf-8
# 响应体
<!DOCTYPE html>
	<head><title>首页</title></head>
	<body><h1>hello world!</h1></body>
</html>

获得页面响应

pip install requests

python 复制代码
import requests
head = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; ×64)" }
response=requests.get("http://books.toscrape.com")
if response.ok:
    print(response.text)
else:
    print("error")

伪装用户访问

python 复制代码
import requests
headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.184.400 QQBrowser/11.3.5190.400"
}
response=requests.get("https://movie.douban.com/top250",headers=headers)
print(response.text)

打包数据

pip install bs4

python 复制代码
from bs4 import BeautifulSoup
import requests

content=requests.get("https://movie.douban.com/top250").text
# 传入BeautifulSoup的构造函数里
# 解析器
soup=BeautifulSoup(content,"html.parser")
# 能根据标签、属性等找出所有符合要求的元素
all_prices=soup.findAll("span",attrs={"class","title"})
for price in all_prices:
    print(price.string) #会把标签包围的文字返回给我们

爬取豆瓣top250

python 复制代码
from bs4 import BeautifulSoup
import requests
# 伪装用户访问
headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Core/1.94.184.400 QQBrowser/11.3.5190.400"
}
# 根据url格式进行自动翻页
for start_num in range(0,250,25):   
    response=requests.get(f"https://movie.douban.com/top250?start={start_num}",headers=headers) #我们就可以用f字符串去格式化
    html=response.text	#打包html
    soup=BeautifulSoup(html,"html.parser")	#用html方式解析
    all_title=soup.findAll("span",attrs={"class":"title"})	#限制特定条件
    for title in all_title:	#遍历所需内容
        title_string=title.string
        if "/" not in title_string:	#限制内容显示
            print(title_string)
相关推荐
郝学胜-神的一滴16 分钟前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
吃我一窝jio1 小时前
Java IO流核心分类与应用
java·开发语言·笔记
Kari112 小时前
医药和制造行业的外文文档批量翻译,排版怎么保住?
开发语言·c#·制造
专注仿真3 小时前
仿真智能体训练:强化学习多目标奖励算法与实战
python·算法·强化学习·afsim智能体
维爱智VR认知学能3 小时前
VR客户端异常诊断包白名单脱敏与受控字段构建实现
python·单元测试·软件工程·数据安全·日志脱敏
isfox4 小时前
Python 装饰器:别被 @ 符号吓到,它就是个"包装盒"
python
Sakura_j_h_4 小时前
用 uv 搭一个命令行待办工具:pyproject、argparse 与全局安装
python·uv·cli·argparse·pyproject
Wellijohn4 小时前
取 Top-K 别乱用 nlargest:我把 20 万条数据从 k=5 测到 k=199000,发现了三个反直觉的坑
python·算法·性能优化
DanCheng-studio4 小时前
毕设 yolov11血液细胞计数识别系统(源码+论文)
python·毕业设计·毕设
阿enna5 小时前
从误检和漏检出发改进YOLO26n:建立错误样本库
人工智能·python·深度学习·yolo·目标检测·机器学习·cnn