【无标题】初入爬虫

主要知识点:
1.标题web是如何交互的
2.requests库的get、post函数的应用
3.response对象的相关函数,属性
4.python文件的打开,保存

好,接下来先安装requests库
在pycharm命令行输入

pip install requests
1
安装好了以后咱先爬个baidu首页

# 爬虫示例,爬取百度页面

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 )
get传参方法实例

#  get传参方法实例

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

response = requests.get("http://httpbin.org/get?name=hezhi&age=20")  # get传参

print( response.status_code ) #状态码

print( response.text )
post传参方法实例

#  post传参方法实例

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

data = {
    "name":"hezhi",
    "age":20
}
response = requests.post( "http://httpbin.org/post" , params=data )  # post传参

print( response.status_code ) #状态码

print( response.text )
绕过反爬机制,以zhihu为例


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

response = requests.get( "http://www.zhihu.com")  #第一次访问知乎,不设置头部信息

print( "第一次,不设头部信息,状态码:"+response.status_code )# 没写headers,不能正常爬取,状态码不是 200

#下面是可以正常爬取的区别,更改了User-Agent字段

headers = {

        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"

}#设置头部信息,伪装浏览器

response = requests.get( "http://www.zhihu.com" , headers=headers )  #get方法访问,传入headers参数,

print( response.status_code ) # 200!访问成功的状态码

print( response.text )


保存百度图片到本地

#保存百度图片到本地

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()#关闭操作,运行完毕后去你的目录看一眼有没有保存成功

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_不欺暗室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值