python的requests模块功能_Python使用requests模块爬取百度翻译

Python使用requests模块爬取百度翻译,模块,数据,的是,持久,字典

Python使用requests模块爬取百度翻译

易采站长站,站长之家为您整理了Python使用requests模块爬取百度翻译的相关内容。

requests模块:

python中原生的一款基于网络请求的模块,功能非常强大,简单便捷,效率极高。

作用:模拟浏览器发请求。

提示:老版使用 urllib模块,但requests比urllib模块要简单好用,现在学习requests模块即可!

requests模块编码流程

指定url

1.1 UA伪装

1.2 请求参数的处理

2.发起请求

3.获取响应数据

4.持久化存储

环境安装:

pip install requests

案例一:破解百度翻译(post请求)

1.代码如下:

#爬取百度翻译

#导入模块

import requests

import json

#UA伪装:将对应的User-Agent封装到一个字典中

headers = {

'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '

'Chrome/57.0.2987.98 Safari/537.36'}

#网页访问连接

url='https://fanyi.baidu.com/sug'

#处理url携带的参数:封装到字典中

word=input("input a word: ")

data={

'kw': word

}

#请求发送

res=requests.post(url=url,data=data,headers=headers)

#获取响应数据:json()方法返回的是obj(如果确认响应数据是json类型的,才可以使用json())

dic_obj=res.json()

#持久化存储

filename=word+'.json'

fp=open(filename,'w',encoding='utf-8')

json.dump(dic_obj,fp=fp,ensure_ascii=False)

#打印完成提示

print('finish')

其中:

https://fanyi.baidu.com/sug 这个url的定位如下图:

python的requests模块功能_Python使用requests模块爬取百度翻译_第1张图片

2.运行结果

python的requests模块功能_Python使用requests模块爬取百度翻译_第2张图片

2b11c8bd6234bb0c89e390cbe76f95d7.jpg

案例二:爬取搜狗页面数据(get请求)

1.代码如下

import requests

if __name__ == "__main__":

#step_1:指定url

url = 'https://www.sogou.com/'

#step_2:发起请求

#get方法会返回一个响应对象

response = requests.get(url=url)

#step_3:获取响应数据.text返回的是字符串形式的响应数据

page_text = response.text

print(page_text)

#step_4:持久化存储

with open('./sogou.html','w',encoding='utf-8') as fp:

fp.write(page_text)

print('爬取数据结束!!!')

2.运行结果如下:

python的requests模块功能_Python使用requests模块爬取百度翻译_第3张图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。以上就是关于对Python使用requests模块爬取百度翻译的详细介绍。欢迎大家对Python使用requests模块爬取百度翻译内容提出宝贵意见

你可能感兴趣的:(python的requests模块功能_Python使用requests模块爬取百度翻译)