python 爬虫库 u_Python爬虫常用库介绍(requests、BeautifulSoup、lxml、json)

1、requests库

http协议中,最常用的就是GET方法:importrequests

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方法外,还有许多其他方法:

importrequests

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方法介绍

示例:

The Dormouse's story

The Dormouse's story

Once upon a time there were three little sisters; and their names were

,

Lacie and

Tillie;

and they lived at the bottom of a well.

...

"""

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

(1).通过标签名查找

print(soup.select('title')) #筛选所有为title的标签,并打印其标签属性和内容#[

The Dormouse's story]

print(soup.select('a')) #筛选所有为a的标签#[, Lacie, Tillie]

print(soup.select('b')) #筛选所有为b的标签,并打印#[The Dormouse's story]

(2).通过类名查找

print soup.select('.sister') #查找所有class为sister的标签,并打印其标签属性和内容#[, Lacie, Tillie]

(3).通过id名查找

print soup.select('#link1') #查找所有id为link1的标签,并打印其标签属性和内容#[]

(4).组合查找

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

print soup.select('p #link1')#[]

直接子标签查找

print soup.select("head > title")#[

The Dormouse's story]

(5).属性查找

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

print soup.select("head > title")#[

The Dormouse's story]

print soup.select('a[href="http://example.com/elsie"]')#[]

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

print soup.select('p a[href="http://example.com/elsie"]')#[]

BeautifulSoup库例句:

from bs4 importBeautifulSoupimportrequests

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 importetree

text= '''

'''

#利用etree.HTML,将字符串解析为HTML文档

html =etree.HTML(text)#按字符串序列化HTML文档

result =etree.tostring(html)print(result)

输出结果如下:

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

4、json库

函数描述

json.dumps

将python对象编码成JSON字符串

json.loads

将已编码的JSON字符串解析为python对象

1. json.dumps的使用

#!/usr/bin/python

importjson

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

importjson

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

jsonStr=json.dumps(data)print(jsonStr)

jsonObj=json.loads(jsonStr)print(jsonObj)#获取集合第一个

for i injsonObj:print(i['name'])

输出结果为:

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

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

张三

李四`

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Python 编写爬虫通常需要用到 requests ,以下是使用 requests 进行爬虫的基本步骤: 1. 导入 requests ```python import requests ``` 2. 发送请求 使用 requests 的 get() 或 post() 方法发送请求,传入目标网址作为参数。例如: ```python response = requests.get('http://www.example.com') ``` 3. 处理响应 获得响应后,可以通过 response 对象的属性和方法来获取响应信息。例如: ```python # 获取响应状态码 status_code = response.status_code # 获取响应内容 content = response.content # 获取响应头 headers = response.headers # 获取 Cookies cookies = response.cookies ``` 4. 解析响应 通常我们需要对响应进行解析,获取有用的数据。使用 BeautifulSouplxml 可以方便地进行 HTML 解析,使用 json 可以解析 JSON 数据。例如: ```python # 使用 BeautifulSoup 解析 HTML from bs4 import BeautifulSoup soup = BeautifulSoup(response.content, 'html.parser') title = soup.title.text # 使用 json 解析 JSON 数据 import json data = json.loads(response.content) ``` 5. 处理异常 在请求过程中可能会出现各种异常,例如网络连接异常、服务器返回错误等。使用 try-except 语句可以处理这些异常。例如: ```python try: response = requests.get('http://www.example.com') response.raise_for_status() except requests.exceptions.RequestException as e: print(e) ``` 以上是使用 requests 进行爬虫的基本步骤,具体使用时需要根据实际情况进行调整和补充。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值