最近python太火了,所以也拿来学习一下。按照网上的教程写了一下简单的post数据请求。
我使用的环境python3.6,使用的到库有urllib和beautifulsoup
python的安装还是非常简单的,直接到官网下载后安装即可。
第三方库的安装 执行 pip install beautilfulsoup4
pip install requests
当然使用内建的模块urlilib也是可以的。比如下面的使用urllib演示一个post请求代码
from urllib.request import urlopen
from urllib.request import Request
from urllib import parse
req = Request('http://www.thsrc.com.tw/tw/TimeTable/SearchResult')
postData = parse.urlencode([
("StartStation", "977abb69-413a-4ccf-a109-0272c24fd490"),
("EndStation", "2f940836-cedc-41ef-8e28-c2336ac8fe68"),
("SearchDate", "2018/01/06"),
("SearchTime", "10:30"),
("SearchWay", "DepartureInMandarin")
])
# header给的是来源和使用的请求工具浏览器
req.add_header("Origin", "http://www.thsrc.com.tw")
req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36")
resp = urlopen(req, data=postData.encode("utf-8"))
print(resp.read().decode("utf-8"))
使用requests演示一个
import requests
parms = {"StartStation": "977abb69-413a-4ccf-a109-0272c24fd490","EndStation": "2f940836-cedc-41ef-8e28-c2336ac8fe68" ,"SearchDate": "2018/01/06" ,"SearchTime": "10:30" ,"SearchWay": "DepartureInMandarin"}
r = requests.post('http://www.thsrc.com.tw/tw/TimeTable/SearchResult', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit', 'Origin': 'http://www.thsrc.com.tw', }
,json=parms)
print(r.text)