python小白掌握这几个python爬虫入门基础代码实例,python爬虫就学会了一大半

这篇博客适合Python小白,通过10个基础的爬虫代码实例,包括京东、美丽说等页面的爬取,讲解了requests库的常用方法如get、post等,以及如何处理反爬机制。通过阅读,读者可以快速掌握Python爬虫的基本操作。
摘要由CSDN通过智能技术生成

python小白掌握这几个python爬虫入门基础代码实例,python爬虫就学会了一大半

如何安装requests库(安装好python的朋友可以直接参考,没有的,建议先装一哈python环境)

windows用户,Linux用户几乎一样:

打开cmd输入以下命令即可,如果python的环境在C盘的目录,会提示权限不够,只需以管理员方式运行cmd窗口

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

Linux用户类似(ubantu为例): 权限不够的话在命令前加入sudo即可

sudo pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

python爬虫入门基础代码实例如下

1.Requests常用方法之get方法实例,下面还有传参实例

#第二个get方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get(“http://httpbin.org/get”) #get方法
print( response.status_code ) #状态码
print( response.text )

2. Requests put方法实例

#第四个 put方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.put(“http://httpbin.org/put”) # put方法访问
print( response.status_code ) #状态码
print( response.text )

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

#第三个 post方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.post(“http://httpbin.org/post”) #post方法访问
print( response.status_code ) #状态码
print( response.text )

4.Requests爬取BD页面并打印页面信息

#第一个爬虫示例,爬取百度页面
import requests #导入爬虫的库,不然调用不了爬虫的函数
response = requests.get(“http://www.baidu.com”) #生成一个response对象
response.encoding = response.apparent_encoding #设置编码格式
print(“状态码:”+ str( response.status_code ) ) #打印状态码
print(response.text)#输出爬取的信息

5.Requests常用方法之get方法传参实例(1)

如果需要传多个参数只需要用&符号连接即可如下

#第五个 get传参方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get(“http://httpbin.org/get?name=hezhi&age=20”) # get传参
print( response.status_code ) #状态码
print( response.text )

6.Requests常用方法之get方法传参实例(2)

params用字典可以传多个

#第六个 get传参方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
data = {
“name”:“hezhi”,
“age”:20
}
response = requests.get( “http://httpbin.org/get” , params=data ) # get传参
print( response.status_code ) #状态码
print( response.text )

7.Requests常用方法之post方法传参实例(2) 和上一个有没有很像

#第七个 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 )

8.关于绕过反爬机制,以知呼为例

#第好几个方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get( “http://www.zhihu.com”) #第一次访问知乎,不设置头部信息
print( “第一次,不设头部信息,状态码:”+response.status_code )# 没写headers,不能正常爬取,状态码不是 200
#下面是可以正常爬取的区别,更改了User-Agent字段
headers = {

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值