1.打开12306网站,查找Doc下面的Hearders部分,若有origin和user_Agent要放入请求头。user_Agent是模拟浏览登录,防爬虫
curl代码如下:
curl -X POST -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" -H "Cache-Control: no-cache" -H "Postman-Token: 6a086c50-a8b1-40e0-ba43-6bcbe7c45071" -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "leftTicketDTO.train_date=2017-03-15" -F "leftTicketDTO.from_station=SHH" -F "leftTicketDTO.to_station=YNG" -F "purpose_codes=ADULT" "https://kyfw.12306.cn/otn/leftTicket/init"
2. 用python3.5的urllib包来发送请求
#用urllib包发送请求 #1.用urlopen发送请求相当于requests(post,data=date,header=header) from urllib.request import urlopen #2.Request打开Url from urllib.request import Request #3.parse放入body from urllib import parse #打开的地址 req=Request("https://kyfw.12306.cn/otn/leftTicket/init") #放入body部分,要用parse参数,它是一个个元组 postdate=parse.urlencode([ ("leftTicketDTO.train_date","2017-03-15"), ("leftTicketDTO.from_station","SHH"), ("leftTicketDTO.to_station","YNG"), ("purpose_codes","ADULT") ]) # req.add_header("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36") resp=urlopen(req,data=postdate.encode("utf-8")) #将请求的结果用utf-8读取出来 print(resp.read().decode("utf-8"))