【问题标题】:Unable to exit a loop when the browser reaches the bottom of a webpage浏览器到达网页底部时无法退出循环
【发布时间】:2018-10-16 10:03:45
【问题描述】:

我用 python 结合 selenium 编写了一个脚本来解析网页中所有可用的咖啡店名称。该网页启用了延迟加载方法,因此我可以在每个滚动条中看到 40 个名称。如果我滚动 2 次,则可见名称的数量为 80,依此类推。

该网页中有 125 个名称。我下面的脚本可以到达该页面的底部,处理所有滚动,但无法跳出循环以打印内容。

到目前为止,这是我的脚本:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 4)
driver.get("https://www.yellowpages.ca/search/si/1/coffee/all%20states")

itemlist = []
while True:
    for elem in wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME,"listing__name--link"))):
        if elem.text not in itemlist:
            itemlist.append(elem.text)

    try:
        driver.execute_script("arguments[0].scrollIntoView();",elem)
    except Exception:break

for item in itemlist:
    print(item)

driver.quit()

该页面的内容不会动态生成,因此我可以使用requests 获取它们,只需更改网址的这部分/si/1/coffee/ 的数量。但是,我想使用 selenium 控制滚动来获取它们。

后记:我不想用driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")for item in range(3): elem.send_keys(Keys.END) 解决,因为我已经成功使用它们了。

我只需要知道如何在任何条件下跳出循环。

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver web-scraping


    【解决方案1】:

    您可以尝试实现以下条件:如果条目数在超时内保持不变,则打破循环

    itemlist = []
    while True:
        for elem in wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME,"listing__name--link"))):
            if elem.text not in itemlist:
                itemlist.append(elem.text)
        current_len = len(driver.find_elements_by_class_name("listing__name--link"))
        try:
            driver.execute_script("arguments[0].scrollIntoView();",elem)
            wait.until(lambda driver: len(driver.find_elements_by_class_name("listing__name--link")) > current_len)
        except Exception:break
    
    for item in itemlist:
        print(item)
    
    driver.quit()
    

    【讨论】:

    • 很高兴再次找到您@sir Andersson。我尝试了您的脚本,但循环仍在运行。脚本无法摆脱它。
    • @Topto ,是的,我被itemlist 弄糊涂了:我以为这是一个节点列表,但它是一个字符串列表...检查更新
    【解决方案2】:

    while True 循环中,将布尔变量done 设置为True。每当您将项目添加到列表时,将其设置为 false。

    如果done = True,则在循环中断之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-07
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      相关资源
      最近更新 更多