1、requests库

http协议中,最常用的就是GET方法:
import requests response = requests.get('http://www.baidu.com')
print(response.status_code) # 打印状态码
print(response.url) # 打印请求url
print(response.headers) # 打印头信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印网页源码
print(response.content) #以字节流形式打印
除此GET方法外,还有许多其他方法:
import requests

requests.get('http://httpbin.org/get')
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')

2、BeautifulSoup库

BeautifulSoup库主要作用:

经过Beautiful库解析后得到的Soup文档按照标准缩进格式的结构输出,为结构化的数据,为数据过滤提取做出准备。

Soup文档可以使用find()和find_all()方法以及selector方法定位需要的元素:
1. find_all()方法

soup.find_all('div',"item") #查找div标签,class="item"

find_all(name, attrs, recursive, string, limit, **kwargs)
@PARAMS:
name: 查找的value,可以是string,list,function,真值或者re正则表达式
attrs: 查找的value的一些属性,class等。
recursive: 是否递归查找子类,bool类型
string: 使用此参数,查找结果为string类型;如果和name搭配,就是查找符合name的包含string的结果。
limit: 查找的value的个数
**kwargs: 其他一些参数
2. find()方法

find()方法与find_all()方法类似,只是find_all()方法返回的是文档中符合条件的所有tag,是一个集合,find()方法返回的一个Tag

3、select()方法

soup.selector(div.item > a > h1) 从大到小,提取需要的信息,可以通过浏览器复制得到。

select方法介绍

示例:

<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""

在写css时,标签名不加任何修饰,类名前加点,id名前加 #,我们可以用类似的方法来筛选元素,用到的方法是soup.select(),返回类型是list。

(1).通过标签名查找

print(soup.select('title')) #筛选所有为title的标签,并打印其标签属性和内容
# [<title>The Dormouse's story</title>] print(soup.select('a')) #筛选所有为a的标签
# [<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] print(soup.select('b')) #筛选所有为b的标签,并打印
# [<b>The Dormouse's story</b>]

(2).通过类名查找

print soup.select('.sister')    #查找所有class为sister的标签,并打印其标签属性和内容
# [<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

(3).通过id名查找

print soup.select('#link1') #查找所有id为link1的标签,并打印其标签属性和内容
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

(4).组合查找

组合查找即和写class文件时,标签名与类名、id名进行的组合原理是一样的,例如查找p标签中,id等于link1的内容,二者需要空格分开。

print soup.select('p #link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

直接子标签查找

print soup.select("head > title")
#[<title>The Dormouse's story</title>]

(5).属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

print soup.select("head > title")
#[<title>The Dormouse's story</title>] print soup.select('a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格。

print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

BeautifulSoup库例句:

from bs4 import BeautifulSoup
import requests f = requests.get(url,headers=headers)
soup = BeautifulSoup(f.text,'lxml') for k in soup.find_all('div',class_='pl2'): #找到div并且class为pl2的标签
b = k.find_all('a') #在每个对应div标签下找a标签,会发现,一个a里面有四组span
n.append(b[0].get_text()) #取第一组的span中的字符串

3、lxml库

lxml 是 一个HTML/XML的解析器,主要的功能是如何解析和提取 HTML/XML 数据。

示例如下:

# 使用 lxml 的 etree 库
from lxml import etree text = '''
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a> # 注意,此处缺少一个 </li> 闭合标签
</ul>
</div>
''' #利用etree.HTML,将字符串解析为HTML文档
html = etree.HTML(text) # 按字符串序列化HTML文档
result = etree.tostring(html) print(result)

输出结果如下:

<html><body>
<div>
<ul>
<li class="item-0"><a href="link1.html">first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>
</ul>
</div>
</body></html>

可以看到。lxml会自动修改HTML代码。例子中不仅补全了li标签,还添加了body,html标签。

4、json库

函数 描述
json.dumps 将python对象编码成JSON字符串
json.loads 将已编码的JSON字符串解析为python对象
1. json.dumps的使用
#!/usr/bin/python
import json data = [ { 'name' : '张三', 'age' : 25}, { 'name' : '李四', 'age' : 26} ] jsonStr1 = json.dumps(data) #将python对象转为JSON字符串
jsonStr2 = json.dumps(data,sort_keys=True,indent=4,separators=(',',':')) #让JSON数据格式化输出,sort_keys:当key为文本,此值为True则按顺序打印,为False则随机打印
jsonStr3 = json.dumps(data, ensure_ascii=False) #将汉字不转换为unicode编码 print(jsonStr1)
print('---------------分割线------------------')
print(jsonStr2)
print('---------------分割线------------------')
print(jsonStr3)

输出结果:

[{"name": "\u5f20\u4e09", "age": 25}, {"name": "\u674e\u56db", "age": 26}]
---------------分割线------------------
[
{
"age":25,
"name":"\u5f20\u4e09"
},
{
"age":26,
"name":"\u674e\u56db"
}
]
---------------分割线------------------
[{"name": "张三", "age": 25}, {"name": "李四", "age": 26}]
2. json.loads的使用
#!/usr/bin/python
import json data = [ { 'name' : '张三', 'age' : 25}, { 'name' : '李四', 'age' : 26} ] jsonStr = json.dumps(data)
print(jsonStr) jsonObj = json.loads(jsonStr)
print(jsonObj)
# 获取集合第一个
for i in jsonObj:
print(i['name'])

输出结果为:

[{"name": "\u5f20\u4e09", "age": 25}, {"name": "\u674e\u56db", "age": 26}]

[{'name': '张三', 'age': 25}, {'name': '李四', 'age': 26}]

张三
李四`

Python爬虫常用库介绍(requests、BeautifulSoup、lxml、json)的更多相关文章

  1. [python爬虫]Requests-BeautifulSoup-Re库方案--Requests库介绍

    [根据北京理工大学嵩天老师“Python网络爬虫与信息提取”慕课课程编写  文章中部分图片来自老师PPT 慕课链接:https://www.icourse163.org/learn/BIT-10018 ...

  2. 爬虫-Python爬虫常用库

    一.常用库 1.requests 做请求的时候用到. requests.get("url") 2.selenium 自动化会用到. 3.lxml 4.beautifulsoup 5 ...

  3. python 爬虫(一) requests+BeautifulSoup 爬取简单网页代码示例

    以前搞偷偷摸摸的事,不对,是搞爬虫都是用urllib,不过真的是很麻烦,下面就使用requests + BeautifulSoup 爬爬简单的网页. 详细介绍都在代码中注释了,大家可以参阅. # -* ...

  4. python爬虫常用库和安装 -- windows7环境

    1:urllib  python自带 2:re      python自带 3:requests     pip install requests 4:selenium      需要依赖chrome ...

  5. Python爬虫常用库安装

    建议更换pip源到国内镜像,下载会快很多:https://www.cnblogs.com/believepd/p/10499844.html requests pip3 install request ...

  6. Python 爬虫常用库(九)

  7. 【Python】在Pycharm中安装爬虫库requests , BeautifulSoup , lxml 的解决方法

    BeautifulSoup在学习Python过程中可能需要用到一些爬虫库 例如:requests BeautifulSoup和lxml库 前面的两个库,用Pychram都可以通过 File--> ...

  8. Python的标准库介绍与常用的第三方库

    Python的标准库介绍与常用的第三方库 Python的标准库: datetime:为日期和时间的处理提供了简单和复杂的方法. zlib:以下模块直接支持通用的数据打包和压缩格式:zlib,gzip, ...

  9. Python爬虫利器一之Requests库的用法

    前言 之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助.入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取.那么这一节来 ...

  10. (转)Python爬虫利器一之Requests库的用法

    官方文档 以下内容大多来自于官方文档,本文进行了一些修改和总结.要了解更多可以参考 官方文档 安装 利用 pip 安装 $ pip install requests 或者利用 easy_install ...

随机推荐

  1. 结合RNN与Transformer双重优点,深度解析大语言模型RWKV

    本文分享自华为云社区<[云驻共创]昇思MindSpore技术公开课 RWKV 模型架构深度解析>,作者:Freedom123. 一.前言 Transformer模型作为一种革命性的神经网络 ...

  2. 【workerman】uniapp+thinkPHP5使用GatewayWorker实现实时通讯

    前言 之前公司需要一个内部的通讯软件,就叫我做一个.通讯软件嘛,就离不开通讯了,然后我就想到了长连接.这里本人用的是GatewayWorker框架. 什么是GatewayWorker框架? Gatew ...

  3. JS中this的几种指向

    这些this的指向,是当我们调用函数的时候确定的.调用方式的不同决定了this的指向不同一般指向我们的调用者.普通函数调用          window.定时器函数             wind ...

  4. springboot异常解决

    问题解决 问题解释 出现这个问题表示拦截器或控制器的某个请求处理方法返回了一个与请求路径相同的视图名称,导致视图解析器循环地尝试解析并渲染这个视图,从而引发循环视图路径的异常. 问题分析 原先的jav ...

  5. 洛谷P1378

    这道题需要处理的信息比较多,需要注意的是一个油滴扩展后可能会包含其他的点 #include <iostream> #include <utility> #include < ...

  6. 数据仓库建模工具之一——Hive学习第一天

    hive分布式搭建文档 谷歌浏览器下载网址:Google Chrome – Download the fast, secure browser from Google 华为云镜像站:https://m ...

  7. oeasy教您玩转vim - 005 - # 程序本质

    ​ 程序本质 回忆上次内容 py 的程序是按照顺序 一行行挨排解释执行的 我们可以 python3 -m pdb hello.py 来对程序调试 调试的目的是去除 bug 别害怕 bug bug 会有 ...

  8. Python爬虫(5-10)-编解码、ajax的get请求、ajax的post请求、URLError/HTTPError、微博的cookie登录、Handler处理器

    五.编解码(Unicode编码) (1)GET请求 所提方法都在urllib.parse.路径下 get请求的quote()方法(适用于只提交一两个参数值) url='http://www.baidu ...

  9. ComfyUI进阶:Comfyroll插件 (四)

    ComfyUI进阶:Comfyroll插件 (四) 前言: 学习ComfyUI是一场持久战,而Comfyroll 是一款功能强大的自定义节点集合,专为 ComfyUI 用户打造,旨在提供更加丰富和专业 ...

  10. 关于导入react native项目导致运行异常的那些事

    从git上导入公司的项目,在本地运行的时候,项目无法运行.sdk,jdk,node都是使用公司规定的版本,项目中的local.properties文件sdk.dir路径也换成了自己本地的目录,结果就在 ...