作者:wuyanting67412 | 来源:互联网 | 2023-05-18 01:32
一、一些基本的库1、requests库:requests是用python语言基于urllib编写的,采用的是Apache2Licensed开源协议的HTTP库,默认安装好python之后,
一、一些基本的库
1、requests 库:
requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装。
2、requests 库的一些基本函数:
requests 库的网页请求函数
函数 |
说明 |
get(url [, timeout=n]) |
对应HTTP的GET方式,设定请求超时时间为n秒 |
post(url, data={'key':'value'}) |
对应HTTP的POST方式,字典用于传输客户数据 |
delete(url) |
对应HTTP的DELETE方式 |
head(url) |
对应HTTP的HEAD方式 |
options(url) |
对应HTTP的OPTIONS方式 |
put(url, data={'key':'value'}) |
对应HTTP的PUT方式,字典用于传输客户数据 |
get方法,它能够获得url的请求,并返回一个response对象作为响应。
response对象的属性
属性 |
说明 |
status_code |
HTTP请求的返回状态 |
encoding |
HTTP响应内容的编码方式 |
text |
HTTP响应内容的字符串形式 |
content |
HTTP响应内容的二进制形式 |
response对象的方法
方法 |
说明 |
|
若http响应内容中包含json格式数据, 则解析json数据 |
|
|
(常见的HTTP状态码:200 - 请求成功,301 - 资源(网页等)被永久转移到其它URL,404 - 请求的资源(网页等)不存在,500 - 内部服务器错误)。
3、BeautifulSoup 库:
Beautiful Soup是python的一个HTML或XML的解析库,我们可以用它来方便的从网页中提取数据,它拥有强大的API和多样的解析方式。
二、我的第一个Python爬虫
1、运用 requests 库的 get() 函数访问 360搜索主页并打印相应的属性:
import requests
for i in range(20):
r=requests.get("https://hao.360.com/")
r.encoding='utf-8'
print("第{}次爬取".format(i+1))
print("返回状态:{}".format(r.status_code))
print("网页内容的长度:{}".format(len(r.text)))
print("text 的内容:{}".format(r.text))
print("content 属性所返回的网页长度:{}".format(len(r.content)))
运行结果如下图:
![](https://img.php1.cn/3cd4a/1eebe/cd5/4fae50aeee651818.webp)
2、利用 BeautifulSoup 对一个简单的 HTML 页面保存为字符串进行操作:
html 文本为:
html='''
我得第一个标题
我得第一个段落。
row 1, cell 1 |
row 1, cell 2 |
row 2, cell 1 |
row 2, cell 2 |
'''
从html文本中获取soup:
from bs4 import BeautifulSoup
# 这里指定解析器为html.parser(python默认的解析器)
soup = BeautifulSoup(html,'html.parser')
printf(type(soup))
# 输出:
获取 head 内容:
print("head 标签内容和学号 后两位:",html.head,'学号后两位 18 ')
输出为:
![](https://img.php1.cn/3cd4a/1eebe/cd5/780a3060eeed6a4e.webp)
获取 body 标签内容:
print("body 标签的内容:",soup.body)
输出为:
![](https://img.php1.cn/3cd4a/1eebe/cd5/4283cd4bbba41b87.png)
获取 id 为 frist 的标签对象:
first=soup.select('#first')
print("first 标签的内容:{}".format(first))
print(type(first))
输出为:
![](https://img.php1.cn/3cd4a/1eebe/cd5/5b97d3b808d031e2.webp)
获取 html 页面的中文字符(采用正则表达式):
import re
pat=re.compile(r'[\u4e00-\u9fa5]+')
result=pat.findall(html)
输出为:
![](https://img.php1.cn/3cd4a/1eebe/cd5/43a754c811e7ec5c.webp)
以上就是我的第一个python爬虫程序。