簡體   English   中英

使用python-requests發送get請求

[英]Sending get request using python-requests

發送帶有查詢字符串的get請求,但是requests正在剝離查詢字符串。 我試圖用編碼它urllib.parse.urlencode()但仍是結果相同與requests 任何幫助請...

import requests

url = 'https://www.booking.com/searchresults.html'
params = { 
    'checkin_monthday': '19',
    'checkin_year': '2018',
    'checkout_month': '4',
    'checkout_monthday': '20',
    'checkout_year': '2018',
    'class_interval': 1,
    'dest_id': -1022488,
    'dest_type': 'city',
    'dtdisc': 0,
    'from_sf': 1,
    'group_adults': 2,
    'group_children':   0,
    'inac': 0,
    'index_postcard': 0,
    'label': 'gen1',
    'label_click': 'undef',
    'no_rooms': 1,
    'offset': 0,
    'postcard': 0,
    'raw_dest_type': 'city',
    'room1': 'A,A',
    'sb_price_type': 'total',
    'sb_travel_purpose': 'business',
    'src': 'index',
    'src_elem': 'sb',
    'ss': 'Pokhara',
    'ss_all': 0,
    'ssb': 'empty',
    'sshis': 0,
    'ssne': 'Pokhara',
    'ssne_untouched': 'Pokhara',
}

# import urllib
# formatted_query_string = urllib.parse.urlencode(payload)
# url = url + '?' + formatted_query_string

r = requests.get(url, params=params)
print(r.url)

# output
# https://www.booking.com/searchresults.html?dest_id=-1022488;est_type=city;ss=Pokhara  

tl; dr

您的代碼很好,不需要使用urllib 之所以獲得“剝離” URL,是因為這不是您要查找的初始 URL。

說明

如果檢查requests 源代碼 ,則可以發現r.url

Final URL location of Response

所以r.url 不是您請求的URL,這是您(最終)重定向到的URL。 您可以進行一個簡單的測試:

from requests import Request, Session


url = 'https://www.booking.com/searchresults.html'  # your url

params = {  # I intentionally shortened this dict for testing purposes
    'checkin_monthday': '19',
    'checkin_year': '2018',
    'checkout_monthday': '20',
    'checkout_year': '2018',
}

req = Request('GET', url, params=params)
prepped = req.prepare()
print(prepped.url)  # you send this URL ...

s = Session()
resp = s.send(prepped)
print(resp.url)  # ... but you are redirected to this URL (same as your r.url)

輸出:

https://www.booking.com/searchresults.html?checkin_year=2018&checkin_monthday=19&checkout_monthday=20&checkout_year=2018
https://www.booking.com/

這里會發生什么:

  1. 您的python腳本發送帶有所有參數的請求。
  2. 服務器處理您請求的內容並以HTTP/1.1 301 Moved Permanently作出響應。 重定向位置可以在標題中找到: Location: https://www.booking.com/searchresults.html?dest_id=-1022488;est_type=city;ss=Pokhara ;est_type= Location: https://www.booking.com/searchresults.html?dest_id=-1022488;est_type=city;ss=Pokhara
  3. requests會收到此響應,然后轉到該位置。 位置URL放入r.url屬性。

這就是為什么初始URL和最終URL不同的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM