打开页面后,如何使用urllib2或Mechanize发送Ajax发布请求?

时间:2013-07-31 06:33:46

标签: ajax post python-2.7 urllib2 mechanize

这是我工作的页面:www.walmart.com/ip/Sony-Xperia-ZL-LTE-C6506-5-Smartphone-Unlocked/24566601

在此页面上,有3种颜色选项可用于设备&每当我点击其中一个颜色框时,设备的颜色变体的价格就会通过Ajax Post请求加载到服务器。

我正在尝试使用Python发送此请求,下面是我到目前为止使用的代码。

代码1:

user_agent = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1;Trident/5.0)'
values = {'ajaxCalls':'AjaxUrl|/catalog/fetch_dynamic_data.do?item_id=24566602|CallbackFunction|WALMART.bot.AjaxInterface.handleSuccess_DynamicData|RtnRespType|json|timeoutSetting|300|'}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(colorlink, data, headers)
response = urllib2.urlopen(req)
page = response.read()
soup = BeautifulSoup(page)

colorlink是我上面提到的网址

代码2:

values = {'ajaxCalls':'AjaxUrl|/catalog/fetch_dynamic_data.do?item_id=24566602|CallbackFunction|WALMART.bot.AjaxInterface.handleSuccess_DynamicData|RtnRespType|json|timeoutSetting|300|'}               
user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7"
headers = { 'User-Agent' : user_agent }
req = mechanize.Request(colorlink, values,headers)
cj.add_cookie_header(req)
res = mechanize.urlopen(req)
soup = BeautifulSoup(res)

colorlink是上面提到的网址。

我从其中一个stackoverflow问题中复制了机械化代码,并试图将它用于我的案例,但它没有用。我遇到 TypeError 可能是因为变量,机械化与di​​ct有关。

另外,我无法在POST参数中发送 Timestamp 值,因为它需要当前时间,我不知道该怎么做。

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以从timestamp获取time.time()。另外,我会选择requests

import requests
import time

REFERER = "http://www.walmart.com/ip/Sony-Xperia-ZL-LTE-C6506-5-Smartphone-Unlocked/24566601"
ORIGIN = "http://www.walmart.com"

timestamp = str(time.time()).replace(".", "")
URL = "http://www.walmart.com/catalog/ajaxBridgeInterface.do?timestamp=%s" % timestamp

data = {'ajaxCalls': 'AjaxUrl|/catalog/fetch_dynamic_data.do?item_id=24566602|CallbackFunction|WALMART.bot.AjaxInterface.handleSuccess_DynamicData|RtnRespType|json|timeoutSetting|300|',
        'timestamp': timestamp}

response = requests.post(URL, data=data, headers={'Referer': REFERER, 'Origin': ORIGIN})

print response.json()

UPD:这是一个使用selenium的例子:

from selenium import webdriver
import time


driver = webdriver.Firefox()
driver.get('http://www.walmart.com/ip/Sony-Xperia-ZL-LTE-C6506-5-Smartphone-Unlocked/24566601')

elements = driver.find_elements_by_class_name('SwatchAnchor')

for element in elements:
    element.click()
    time.sleep(2)
    print driver.find_element_by_class_name('bigPriceText1').text + driver.find_element_by_class_name('smallPriceText1').text 

driver.close()

希望有所帮助。