您的位置:首页 > 编程语言 > Python开发

python爬取网站数据(post)方式

2018-01-06 13:28 316 查看
最近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) AppleWe
4000
bKit',  'Origin': 'http://www.thsrc.com.tw', }
,json=parms)

print(r.text)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: