4.17

Python爬虫request模块

首先安装:pip install requests

爬取搜狗尝试:

# 案例1. 抓取搜狗搜索内容
kw = input("请输⼊你要搜索的内容:")
response =
requests.get(f"https://www.sogou.com/web?query=
{kw}") # 发送get请求
# print(response.text) # 直接拿结果(⽂本)
with open("sogou.html", mode="w", encoding="utf8") as f:
 f.write(response.text)

百度翻译案例:

# 案例2.抓取百度翻译数据
# 准备参数
kw = input("请输⼊你要翻译的英语单词:")
dic = {
 "kw": kw # 这⾥要和抓包⼯具⾥的参数⼀致.
}
# 请注意百度翻译的sug这个url. 它是通过post⽅式进⾏提交
的. 所以我们也要模拟post请求
resp =
requests.post("https://fanyi.baidu.com/sug",
data=dic)
# 返回值是json 那就可以直接解析成json
resp_json = resp.json()
# {'errno': 0, 'data': [{'k': 'Apple', 'v': 'n.
苹果公司,原称苹果电脑公司'....
print(resp_json['data'][0]['v']) # 拿到返回字典中的
内容

 

posted @ 2021-04-17 16:35  {hunter}ZY  阅读(63)  评论(0编辑  收藏  举报