requests.get
# 安装request pip install requests
# import requests
# url = "http://www.sogou.com/web?query=周杰伦"
# resp = requests.get(url) # 地址栏链接 一定是get方式提交
# print(resp)
# print(resp.text) # 拿到网页源代码 访问被拦截# import requests
# url = "http://www.sogou.com/web?query=周杰伦"
# dic = {
# "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
# }
# resp = requests.get(url, headers=dic) # 地址栏链接一定是get方式提交
# # 处理一个小小的反爬
# print(resp)
# print(resp.text) # 拿到网页源代码 访问被拦截import requests
query = input("输入一个你喜欢的明星:")
url = f"http://www.sogou.com/web?query={query}"
dic = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
resp = requests.get(url, headers=dic) # 地址栏链接一定是get方式提交# 处理一个小小的反爬
print(resp)
print(resp.text) # 拿到网页源代码 访问被拦截
request.get中url拼接
"""
File: 04request入门_03.py
Author: chde_wang
Date: 2021-04-19 16:59:47
Description:
"""
import requests
# network-XHR 第二次请求链接
url = "https://movie.douban.com/j/chart/top_list"
# 重新封装参数
param = {"type": "24","interval_id": "100:90","action": "","start": 0,"limit": 20,
}
header = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}
resp = requests.get(url=url, params=param,headers=header)
# print(resp.request.url)
print(resp.request.headers)
print(resp.text)
print(resp.json())
# 滚动加载的时候查看query string数据的变化resp.close() # 关掉resp,要不然报错,还有文件的关闭
注意:在使用完resp后,需要关闭,否则多次访问会报错。
request.post
import requests
url = "http://www.fanyi.baidu.com/sug"
s = input("请输入你要翻译的英文单词:")
dat = {"kw":s # Form data
}
# 发送post请求 发送的数据必须放在字典中 通过data参数进行传递
resp = requests.post(url, data=dat)
print(resp.json()) # 将服务器返回的内容直接转换为json ->dict