[英]Curl vs requests python 3
我正在對服務發出卷曲請求:
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塊
如果您在環境中配置了代理,請在會話/請求中也定義它。
例如會話:
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)
當我嘗試以下內容時,我正在輸出。
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
當服務器正在搜索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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.