我试着在python.org中爬行头旗旋转木马进行练习。我使用WebDriverWait来等待在单击触发器后可见的元素,但这些元素无法正常工作。这是我的密码。

# ChromeDriver
driver.get("https://www.python.org/")

hBannerNav = driver.find_elements_by_xpath(
    '//ol[@class="flex-control-nav flex-control-paging"]/li/a')

for i in range(len(hBannerNav)):
    print(hBannerNav[i].text)
    hBannerNav[i].click()
    try:
        self.wait.until(EC.visibility_of_element_located(
            (By.XPATH, '//ul[@class="slides menu"]/li[{}]'.format(i + 1))))
        h1 = driver.find_element_by_xpath(
            '//ul[@class="slides menu"]/li[{}]/div/h1'.format(i + 1))
        print(h1.text)

        # if add a sleep the crawler will work properly and smoothly,
        # but I want to use WebDriverWait only.
        # sleep(1)

    except Exception as e:
        print('error', e)

以下是日志:
# without sleep
1
Functions Defined
2
Compound Data Types
3
error Message:

4
Quick & Easy to Learn
5
All the Flow You’d Expect # wait for a long time but still crawl it

# use sleep
1
Functions Defined
2
Compound Data Types
3
Intuitive Interpretation
4
Quick & Easy to Learn
5
All the Flow You’d Expect

使用presence_of_all_elements_located
# the results by using
h1 = self.wait.until(EC.presence_of_all_elements_located(
    (By.XPATH, '//ul[@class="slides menu"]/li[{}]/div/h1'.format(i + 1))))[0]

1
Functions Defined
2
Compound Data Types
3

4

5

最佳答案

我加载了你的代码,并给了它一个旋转。你基本上做得对;问题是这个slides menu元素有点奇怪。当切换幻灯片时,会有一个淡入淡出的效果,只需几秒钟。在此期间,感兴趣的li/h1被视为“可见”,但幻灯片按钮没有响应!尝试在淡入效果期间自己单击它们。什么都没发生。
在使用Selenium时,我经常遇到这些小的、意外的时间问题,解决方案因情况而异。
通常我会检查按钮是否可点击,但点击性不是这里的问题。
在这里,我通过等待上一张幻灯片的不可见性来实现:

for i in range(len(hBannerNav)):
    print(hBannerNav[i].text)
    hBannerNav[i].click()
    # We don't wait if i == 0 because in that case, there's no previous slide
    if i > 0:
        WebDriverWait(driver, 3).until(
            EC.invisibility_of_element_located((By.XPATH, '//ul[@class="slides menu"]/li[{}]'.format(i))))
    h1 = driver.find_element_by_xpath(
        '//ul[@class="slides menu"]/li[{}]/div/h1'.format(i + 1))
    print(h1.text)

也许还有其他更好的方法来解决这个时间问题,但希望这足以让你摆脱困境。

关于python - Selenium Explicit等待在Python中无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54102592/

10-10 21:47
查看更多