首页 > 解决方案 > Python 使用 While 循环避免重复打印

问题描述

Python Selenium用来解析一些live data(Bets),我用While loop 这是我的代码中的一些逻辑

def parse():
    while True:
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        print(x)

此代码有效,但输出为

1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x

什么是只打印一张的最佳方法?例如像这样

1.54x
13.5x

标签: pythonpython-3.x

解决方案


您可以将第二个变量 ( y) 分配给原始变量 ( x),然后将新值分配给x。然后,在 if 语句中检查它们是否不相等 ( !=)。

编码:

def parse():
    x = ''
    while True:
        y = x
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        if y != x:
            print(x)

推荐阅读