网络编程
位置:首页>> 网络编程>> Python编程>> Python使用requests模块爬取百度翻译

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

作者:Keep__Studying  发布时间:2023-07-31 14:17:22 

标签: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模块爬取百度翻译

2.运行结果

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

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

案例二:爬取搜狗页面数据(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模块爬取百度翻译

来源:https://blog.51cto.com/13760351/2512069

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com