我正在为服务做一个curl post请求:
curl -v --data "cp4=2765&cp3=350&method%3AsearchPC2=Procurar" https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx
我可以看到它成功了,因为我们在响应正文中有一个div结果:
...
<div class="highlighted-result text-left">
<h4 class="subheader">Rua Sacadura Cabral</h4>
<h4 class="subheader">Ímpares de 11 a 233</h4>
<h3 class="subheader">Galiza</h3>
<h2>2765-350 ESTORIL</h2>
</div>
...
有线的事情是,如果我使用python +请求,它不会给我预期的结果,因为上面的curl,我甚至尝试将用户代理设置为与curl相同:
import requests as r
headers_p = {
'User-Agent': 'curl/7.47.0',
'Host': 'www.ctt.pt'
}
payload = {'cp4': 2765, 'cp3': 350, 'method':'', 'searchPC2': 'Procurar'}
req_p = r.post('https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx', data=payload)
print(req_p.text) # doesn't have the the same content as the curl, I need the html block above
但它失败了,服务器没有发送结果html块
答案 0 :(得分:2)
如果您的环境中配置了代理,请在会话/请求中定义代理。
例如,使用会话:
my_proxies = {
'http': 'http://myproxy:8080',
'https': 'https://myproxy:8080'
}
session = requests.Session()
request = requests.Request('POST', 'http://my.domain.com', data=params_template, headers=req_headers, proxies=my_proxies)
prepped = session.prepare_request(request)
response = session.send(prepped)
见文件:
请求http://docs.python-requests.org/en/master/user/quickstart/
会话http://docs.python-requests.org/en/master/user/advanced/
另一个选项可以是安全性,如果您使用ssl有问题,请添加verify = False 例如:
response = requests.get('http://my.domain.com', verify=False)
答案 1 :(得分:0)
当我尝试以下操作时,我会得到输出。
import requests as r
from requests import Response
headers = {'Content-Type': 'application/xml'}
payload = {'cp4': 2765, 'cp3': 350, 'method':'', 'searchPC2': 'Procurar'}
given_url = 'https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx'
req_p = r.post(given_url, data=payload, headers=headers)
print req_p, req_p.text
尝试根据需要解析内容。我得到了输出。
我试图改变headers = {'Content-Type': 'application/x-www-form-urlencoded'}
仍然得到一些输出。
注意:我使用的是python2.7
答案 2 :(得分:0)
请使用以下代码,因为服务器正在搜索json格式。
import requests as r
import json
from requests import Response
headers = {'Content-Type': 'application/json'}
payload = {'cp4': 2765, 'cp3': 350, 'method':'', 'searchPC2': 'Procurar'}
data_json = json.dump(payload)
given_url = 'https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx'
req_p = r.post(given_url, data=data_json, headers=headers)
print req_p, req_p.text