匿名请求被拒绝?

时间:2015-10-02 04:21:55

标签: python python-requests tor data-extraction

我正在尝试学习匿名的http请求并取得了一些成功,但我最近的尝试是不接受我的请求(requesocks.exceptions.HTTPError:400 Client Error)。我使用tor来获取匿名IP。这是我的代码:

from fake_useragent import UserAgent
import requests
import requesocks


def newUserAgent():
    "adds a new User-Agent item to HEADERS dictionary"
    HEADERS['User-Agent'] = UA.random

def newUrl():
    "increments CurrentPage and returns url"
    url = 'http://www.realtor.ca/Residential/Map.aspx#CultureId=1&ApplicationId=1&RecordsPerPage=9&MaximumResults=9&PropertyTypeId=300&TransactionTypeId=2' \
    '&StoreyRange=0-0&OwnershipTypeGroupId=1&BuildingTypeId=1&BedRange=0-0&BathRange=0-0&LongitudeMin=-119.66980648040801&LongitudeMax=-119.58174419403106' \
    '&LatitudeMin=49.822197219797346&LatitudeMax=49.84943388971021&SortOrder=A&SortBy=1&viewState=l&Longitude=-119.487716674805&Latitude=49.8434562683105'  \
    '&CurrentPage=' + str(CURRENT_PAGE + 1) 
    return url


def getDataDict():
    "returns data_dict from msl.ca url"
    # Reset User-Agent in HEADERS, increment CurrentPage in url
    newUserAgent()
    url = newUrl()

    # Check visible IP
    ip = SESSION.get("http://icanhazip.com/")
    print "visible IP is:", ip.text

    # Request the URL 
    response = SESSION.get(url, headers=HEADERS)
    response.raise_for_status() # raise exception if invalid response


def main():
    getDataDict()



#------------------------
#    global objects:
#------------------------

CURRENT_PAGE = 0

UA = UserAgent()
HEADERS = {
'Host': 'www.realtor.ca',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Referer': 'http://www.realtor.ca/Residential/Map.aspx',
'Content-Length': '411',
'Connection': 'keep-alive',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache'
}


#Initialize a new wrapped requests object
SESSION = requesocks.session()
#Use Tor for both HTTP and HTTPS
SESSION.proxies = {'http': 'socks5://localhost:9050', 'https': 'socks5://localhost:9050'}





if __name__ == '__main__':
    main()

我在这里做错了什么? IP打印正常(即对http://icanhazip.com/的请求工作正常,但后续URL没有 - 有什么不同?)

1 个答案:

答案 0 :(得分:0)

服务器正在返回fx:controller="some.package.MyController" 您无法在其中发出包含锚文本(HTTP Error 400. The request URL is invalid.)的HTTP请求。

哈希标记(#)及其后面的所有内容都不会在HTTP请求中发送。大量使用Ajax的站点(如您尝试使用的站点)将使用Javascript读取锚文本,然后发出Ajax请求以更新内容。

通过快速查看他们的网站,来自锚标记的请求通过Ajax请求到URL #CultureId...,帖子正文中包含锚文本。

屏幕截图:HTTP Request for data

从Cookie的外观来看,您需要先向http://www.realtor.ca/api/Listing.svc/PropertySearch_Post发出建立会话Cookie的请求,然后您可以尝试使用搜索参数向/Residential/Map.aspx网址发出请求。它返回一个JSON响应,您必须解析它以对搜索结果执行任何操作。

编辑:此代码适用于我(使用结果打印成功的JSON响应)

PropertySearch_Post
相关问题