首页 文章

Python Web抓取请求遵循重定向

提问于
浏览
3

我正在尝试使用请求模块抓取一个网站 .

使用chrome和inspect元素,我转到url,填写表单并单击继续按钮 . Chrome的检查元素(网络文档)显示了随帖子发送的chrome . 它还显示多个cookie . 该站点重定向到URL,其中包括会话ID .

为了模拟这个,我尝试使用请求 . 我从inspect元素中获取表单数据并将其重新格式化为字典 . 我使用requests.session包含cookie .

import requests

form_data = 'currentCalForm=dep&currentCodeForm=&tripType=oneWay&searchCategory=award&originAirport=JFK&flightParams.flightDateParams.travelMonth=5&flightParams.flightDateParams.travelDay=14&flightParams.flightDateParams.searchTime=040001&destinationAirport=LHR&returnDate.travelMonth=-1000&returnDate.travelDay=-1000&adultPassengerCount=2&adultPassengerCount=1&serviceclass=coach&searchTypeMode=matrix&awardDatesFlexible=true&originAlternateAirportDistance=0&destinationAlternateAirportDistance=0&discountCode=&flightSearch=award&dateChanged=false&fromSearchPage=true&advancedSearchOpened=false&numberOfFlightsToDisplay=10&searchCategory=&aairpassSearchType=false&moreOptionsIndicator=oneWay&seniorPassengerCount=0&youngAdultPassengerCount=0&childPassengerCount=0&infantPassengerCount=0&passengerCount=2'.split('&')

payload = {}
for item in form_data:
    key, value = item.split('=')
    if value:
        payload[key] = value

with requests.session() as s:    
    r = s.post('https://www.aa.com/homePage.do', params = payload, allow_redirects=True)
    print r.headers
    print r.history
    print r.url
    print r.status_code
    with open('x.htm', 'wb') as f:
        f.write(r.text.encode('utf8'))

但是,请求似乎不遵循重定向 . 历史记录为空,网址似乎是我发送的数据,而不是网站返回的数据 . x.htm显示一个网页,但不包含我预期的信息 .

http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history我希望r.url包含重定向的url和r.history以包含http响应代码 .

我究竟做错了什么?

1 回答

  • 2

    好吧你做的似乎是错的 . 我不确定你是如何决定在 https://www.aa.com/homePage.do 发送一个帖子的,但这似乎是一个得到并且不会接受你发送的参数 . 当您单击搜索时,您的浏览器会发送以下帖子: https://www.americanairlines.co.uk/reservation/searchFlightsSubmit.do;jsessionid=XXXXXXXXXXXXXXXXXXX 和参数:

    currentCalForm=dep
    currentCodeFrom=
    tripType=roundTrip
    originAirport=LAX
    flightParams.flightDateParams.travelMonth=10
    flightParams.flightDateParams.travelDay=24
    flightParams.flightDateParams.searchTime=040001
    destinationAirport=JFK
    returnDate.travelMonth=10
    returnDate.travelDay=31
    returnDate.searchTime=400001
    adultPassengerCount=1
    adultPassengerCount=1
    childPassengerCount=0
    hotelRoomCount=1
    serviceclass=coach
    searchTypeMode=matrix
    awardDatesFlexible=true
    originAlternateAirportDistance=0
    destinationAlternateAirportDistance=0
    discountCode=
    flightSearch=revenue
    dateChanged=false
    fromSearchPage=true
    advancedSearchOpened=false
    numberOfFlightsToDisplay=10
    searchCategory=
    aairpassSearchType=false
    moreOptionsIndicator=
    seniorPassengerCount=0
    youngAdultPassengerCount=0
    infantPassengerCount=0
    passengerCount=1
    

    然后这会给你一个html回来 . preety mach你必须发送在浏览器中发送的所有请求 . 你可能更容易用硒来做 .

    我发现这个使用httpfox可能类似于chrome网络 .

相关问题