python做简单爬虫的一些常用组件

文章目录

前言

最近一直在做零散的一次性的爬虫工作,基本都是用python开发的,整理一下python做小规模爬虫开发常用的一些工具类

request

python最简单的发http请求的包,request.get和request.post就可以搞定绝大部分的抓取需求了,postman也提供直接把请求转成request代码的功能

python 复制代码
import requests

url = "https://www.who.int/publications/i/item/9789240087002"

payload = {}
headers = {
  'Cookie': '_cfuvid=ckXDZTR8JfnelALNiB3ROmqSzyj13jtX.4WlS8zKHSw-1722239912266-0.0.1.1-604800000'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

json

类似java里的fastjson包,可以把map对象和json字符串相互转换,转换方法为json.loads(把json字符串转成map对象)和json.dumps(把map对象转成json字符串)

python 复制代码
import json
dict_test={"key":"这是一个测试map"}
text_test=json.dumps(dict_test,ensure_ascii=False)
print(text_test)
dict_test2=json.loads(text_test)
print(dict_test2)

注意json.dumps如果要转换中文的话加一个ensure_ascii=False,要不然结果就会是这样

bs4

bs4是一个做html和xml树解析的包,使用如下

python 复制代码
from bs4 import BeautifulSoup
html=BeautifulSoup(response.text)
html.find_all("div",class_="")

直接构建一个BeatifulSoup对象之后用find函数就可以定位到对应元素(组)

相关推荐
该用户已不存在3 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP5 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805110 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下11 小时前
最终的信号类
开发语言·c++·算法
c8i11 小时前
python中类的基本结构、特殊属性于MRO理解
python
echoarts11 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin050611 小时前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix11 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
Doris_202311 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202312 小时前
Python 模式匹配match case
前端·后端·python