【问题标题】:Selenium getting all of the attributes pythonSelenium 获取所有属性 python
【发布时间】:2015-08-02 02:32:17
【问题描述】:

我正在尝试获取页面上的所有元素,但它具有无限滚动。我尝试向下滚动页面,然后获取属性,但它没有把它们全部捡起来?出于某种原因,我只得到了大约一半?

 driver = webdriver.Firefox()
 driver.get("http://www.amazon.com/gp/pdp/profile/A2A46BUQRGSAB0/ref=cm_cr_dp_pdp")
 lastHeight = driver.execute_script("return document.body.scrollHeight")
 while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(3)
    newHeight = driver.execute_script("return document.body.scrollHeight")
    print newHeight, lastHeight
    if newHeight == lastHeight:
       break
   lastHeight = newHeight
tree = etree.HTML(driver.page_source)
product = tree.xpath('//span[@class="a-size-base product-title pr-multiline-ellipses-container"]//text()')[::3]
print len(product)

【问题讨论】:

  • 我想查看是否有人评论了我列表中的特定产品。所以我只是想在配置文件上获取产品名称。 @birthofearth

标签: python selenium xpath


【解决方案1】:

查看Selenium Python bindings doc,您可以尝试使用等待,无论是隐式的还是显式的。 SO Selenium random timeout exceptions without any message 的这个答案可能有助于实现显式等待实现。

对于隐式等待,您可以尝试类似的方法(未测试):

def reached_bottom(driver):
    try:
        return driver.find_element_by_class_name("no-more")        
    except:
        return False    

driver = webdriver.Firefox()
driver.implicitly_wait(10)    
driver.get("http://www.amazon.com/gp/pdp/profile/A2A46BUQRGSAB0/ref=cm_cr_dp_pdp")

while not reached_bottom(driver):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

product = ... 

我使用了在结尾显示的no-more 类作为停止条件,假设它在到达结尾时被添加到 DOM。但同样,没有测试它。

【讨论】:

    【解决方案2】:

    您需要等待滚动生效。否则,您将在更新完成之前获得源代码。

    简单但不完美的解决方法是使用 time.sleep 并有足够的时间:

    import time
    
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(1)  # <---
    newHeight = driver.execute_script("return document.body.scrollHeight")
    

    【讨论】:

    • 即使我将脚本休眠 5 秒,当此配置文件确实有它时,我仍然没有得到 >25 条评论。
    • @bentest,即使我用浏览器手动操作,75(25 * 3)也是我能得到的最大值。
    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2013-04-05
    相关资源
    最近更新 更多