如何等待页面加载完成?

2024-10-01 11:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获得可用的启动大小(低于$('选项。添加'))来自http://www.neimanmarcus.com/Stuart-Weitzman-Reserve-Suede-Over-the-Knee-Boot-Black/prod179890262/p.prod

我尝试了下面的代码,但它总是在得到大小之前返回。在

# 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,但也失败了。在


Tags: theimportcomconfighttphtmlwwwover
2条回答

使用方式如下:

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

而不是

^{pr2}$

我的理解是正确的:无论代码休眠多长时间,它仍然没有加载鞋子的大小?在

因为您没有使用无头浏览器,所以不会在请求的页面上执行javascript。尝试使用无头浏览器,如PhantomJS。这里是更多headless browsers的列表。在

这里有一个如何使用PhantomJS in Python的方法。在

相关问题 更多 >