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)
相关推荐
lsx2024067 分钟前
SQLite Select 语句详解
开发语言
Dovis(誓平步青云)16 分钟前
基于探索C++特殊容器类型:容器适配器+底层实现原理
开发语言·c++·queue·适配器·stack
R-sz24 分钟前
java流式计算 获取全量树形数据,非懒加载树,递归找儿
java·开发语言·windows
随意02342 分钟前
Qt 事件
开发语言·qt
Gyoku Mint1 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
鸥梨菌Honevid1 小时前
Qt自定义控件(1)——QPaintEvent
开发语言·qt
Code季风1 小时前
深入比较 Gin 与 Beego:Go Web 框架的两大选择
开发语言·golang·go·gin·beego
专注VB编程开发20年2 小时前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
郭庆汝6 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
黄雪超9 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm