使用request.get()在python中对XHR请求的响应不完整

时间:2019-12-05 20:52:17

标签: python ajax python-3.x python-requests xmlhttprequest

我正在尝试使用this服务器上的Python请求,在给定城市中的给定街道上刮除德国邮政编码(PLZ)。我正在尝试应用我学到的here

我想退回的PLZ Schanzäckerstr.中的Nürnberg

import requests

url = 'https://www.11880.com/ajax/getsuggestedcities/schanz%C3%A4ckerstra%C3%9Fe%20n%C3%BCrnberg?searchString=schanz%25C3%25A4ckerstra%25C3%259Fe%2520n%25C3%25BCrnberg'

data = 'searchString=schanz%25C3%25A4ckerstra%25C3%259Fe%2520n%25C3%25BCrnberg'


headers = {"Authority": "wwww.11880.com",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0",
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Accept-Language": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7",
                "Accept-Encoding": "gzip, deflate, br",
                "X-Requested-With": "XMLHttpRequest",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "Content-Length": "400",
                "Origin": "https://www.postleitzahlen.de",
                "Sec-Fetch-Site": "cross-site",
                "Fetch-Mode": "cors",
                "DNT": "1",
                "Connection": "keep-alive",
                "Referer": "https://www.postleitzahlen.de",
               }
multipart_data = {(None, data,)}

session = requests.Session()
response = session.get(url, files=multipart_data, headers=headers)

print(response.text)

上面的代码产生200类型的空响应。我想返回:

'90443'

1 个答案:

答案 0 :(得分:0)

我能够使用nominatim openstreetmap API解决此问题。一个人也可以添加街道号码

import requests
city = 'Nürnberg'
street = 'Schanzäckerstr. 2'

response = requests.get( 'https://nominatim.openstreetmap.org/search', headers={'User-Agent': 'PLZ_scrape'}, params={'city': city, 'street': street[1], 'format': 'json', 'addressdetails': '1'}, )
print(street, ',', [i.get('address').get('postcode') for i in response.json()][0])

确保每秒仅发送一个请求。