Python爬虫常用的几个方法

本文是一篇Python爬虫基础教程,介绍了如何使用requests库进行HTTP的GET、POST、PUT方法请求,并展示了爬取网页内容、保存HTML文件以及下载图片的实际操作。通过这些基本操作,读者可以掌握网络爬虫的基本技能。
摘要由CSDN通过智能技术生成

-- codeing = utf-8 --,开头的这个是设置编码为utf-8 ,写在开头,防止乱码。

爬取强大的BD页面,打印页面信息

# 第一个爬虫示例,爬取百度页面

import requests #导入爬虫的库,不然调用不了爬虫的函数

response = requests.get("http://www.baidu.com")  #生成一个response对象

response.encoding = response.apparent_encoding #设置编码格式

print("状态码:"+ str( response.status_code ) ) #打印状态码

print(response.text)#输出爬取的信息
常用方法之get方法实例,下面还有传参实例

# 第二个get方法实例

import requests #先导入爬虫的库,不然调用不了爬虫的函数

response = requests.get("http://httpbin.org/get")  #get方法

print( response.status_code ) #状态码

print( response.text )

常用方法之post方法实例,下面还有传参实例

# 第三个 post方法实例

import requests #先导入爬虫的库,不然调用不了爬虫的函数

response = requests.post("http://httpbin.org/post")  #post方法访问

print( response.status_code ) #状态码

print( response.text )

put方法实例

# 第四个 put方法实例

import requests #先导入爬虫的库,不然调用不了爬虫的函数

response = requests.put("http://httpbin.org/put")  # put方法访问

print( response.status_code ) #状态码

print( response.text )

# 爬取一个html并保存

import requests

url = "http://www.baidu.com"

response = requests.get( url )

response.encoding = "utf-8" #设置接收编码格式

print("\nr的类型" + str( type(response) ) )

print("\n状态码是:" + str( response.status_code ) )

print("\n头部信息:" + str( response.headers ) )

print( "\n响应内容:" )

print( response.text )

#保存文件
file = open("D:\\爬虫\\baidu.html","w",encoding="utf")  #打开一个文件,w是文件不存在则新建一个文件,这里不用wb是因为不用保存成二进制

file.write( response.text )

file.close()

#保存百度图片到本地

import requests #先导入爬虫的库,不然调用不了爬虫的函数

response = requests.get("https://www.baidu.com/img/baidu_jgylogo3.gif")  #get方法的到图片响应

file = open("D:\\爬虫\\baidu_logo.gif","wb") #打开一个文件,wb表示以二进制格式打开一个文件只用于写入

file.write(response.content) #写入文件

file.close()#关闭操作,运行完毕后去你的目录看一眼有没有保存成功
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值