requests获取URL资源
Get 访问一个网页
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 访问网络资源 requests
## Get 访问一个网页
import requests
# 访问百度
result = requests.get("https://www.baidu.com")
print(result.status_code)
print(result.text)
运行结果
D:\PythonProject>python main.py
200
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></sp....
获取Json对象
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 访问网络资源 requests
# Get 访问一个网页
import requests
# 访问百度
result = requests.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json")
#获取Json对象
print(result.json())
运行结果
D:\PythonProject>python main.py
{'query': {'count': 1, 'created': '2017-12-21T15:38:56Z', 'lang': 'en-US', 'results': {'channel': {'units': {'distance': 'mi', 'pressure': 'in', 'speed': 'mph', 'temperature': 'F'}, 'title': 'Yahoo! Weather - Beijing, Beijing, CN', 'link': 'http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-2151330/', 'description': 'Yahoo! Weather for Beijing, Beijing, CN', 'language': 'en-us', 'lastBuildDate': 'Thu, 21 Dec 2017 11:38 PM CST', 'ttl': '60', 'location': {'city': 'Beijing', 'country': 'China', 'region': ' Beijing'}, 'wind': {'chill': '19', 'direction': '340', 'speed': '4'}, 'atmosphere': {'humidity': '63', 'pressure': '1018.0', 'rising': '0', 'visibility': '16.1'}, 'astronomy': {'sunrise': '7:33 am', 'sunset': '4:53 pm'}, 'image': {'title': 'Yahoo! Weather', 'width': '142', 'height': '18', 'link': 'http://
post 方法
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 访问网络资源 requests
# Get 访问一个网页
import requests
# post 方法
result = requests.post('https://accounts.douban.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'})
#获取Json对象
print(result)
运行结果
D:\PythonProject>python main.py
<Response [200]>
用到了在细究即可,知道访问网络资源很方便即可