2016-05-10 253 views
0

我試圖從http://www.neimanmarcus.com/Stuart-Weitzman-Reserve-Suede-Over-the-Knee-Boot-Black/prod179890262/p.prod如何等待頁面加載完成?

我嘗試下面的代碼獲取可用的引導大小(在$(「option.addedOption」)),但得到了大小之前它總是返回。

# config.url = 'http://www.neimanmarcus.com/Stuart-Weitzman-Reserve-Suede-Over-the-Knee-Boot-Black/prod179890262/p.prod' 
import urllib2 
import requests 
import config 
import time 
from lxml.cssselect import CSSSelector 
from lxml.html import fromstring 

print config.url 
headers = { 
    "Host": "www.neimanmarcus.com", 
    "Connection": "keep-alive", 
    "Content-Length": 106, 
    "Pragma": "no-cache", 
    "Cache-Control": "no-cache", 
    "Accept": "*/*", 
    "Origin": "http://www.neimanmarcus.com", 
    "X-Requested-With": "XMLHttpRequest", 
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", 
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", 
    "Referer": "http://www.neimanmarcus.com/Stuart-Weitzman-Reserve-Suede-Over-the-Knee-Boot-Black/prod179890262/p.prod", 
    "Accept-Language": "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,fr;q=0.2,cs;q=0.2,zh-TW;q=0.2" 
} 
request = urllib2.Request(config.url, headers=headers) 
html = urllib2.urlopen(request) 
time.sleep(10) 
html = html.read() 
print html 
html = fromstring(html) 
sel = CSSSelector('option.addedOption') 
try: 
    options = sel(html) 
    print options 
except Exception as e: 
    print e 

我發現尺寸以請求「http://www.neimanmarcus.com/product.service」(實際上是頭根據該請求的請求報頭創建)得到。

如何獲取整個頁面信息(尤其是啓動大小)?

我也嘗試直接請求http://www.neimanmarcus.com/product.service,但也失敗了。

回答

2

正如我理解正確的話:不管代碼多久睡它仍然沒有加載鞋的大小?

由於您沒有使用無頭瀏覽器,因此您不會在請求的頁面上執行JavaScript。嘗試使用像PhantomJS這樣的無頭瀏覽器。這裏列出更多headless browsers

這裏有一種方法如何使用PhantomJS in Python

+0

謝謝。我會稍後再嘗試。 – Cuero

0

這樣使用它:的

with urllib2.urlopen(request) as response: 
    html = response.read() 
    print html 
    html = fromstring(html) 
    sel = CSSSelector('option.addedOption') 
    try: 
     options = sel(html) 
     print options 
    except Exception as e: 
     print e 

代替

​​