我正在制作一个自动化的python脚本,它在一个循环中打开chromedriver,直到它在驱动程序获得的网页上找到一个特定的元素(使用selenium)。这显然最终会消耗资源,因为它在循环中不断地打开和关闭驱动程序。
有没有一种方法可以使用现有的chromedriver窗口,而不是只在循环上打开和关闭,直到满足条件?
如果这是不可能的,有没有替代的方法,你会推荐吗?
谢谢!
脚本:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import pyautogui
import time
import os
def snkrs():
driver = webdriver.Chrome('/Users/me/Desktop/Random/chromedriver')
driver.get('https://www.nike.com/launch/?s=in-stock')
time.sleep(3)
pyautogui.click(184,451)
pyautogui.click(184,451)
current = driver.current_url
driver.get(current)
time.sleep(3.5)
elem = driver.find_element_by_xpath("//* .
[@id='j_s17368440']/div[2]/aside/div[1]/h1")
ihtml = elem.get_attribute('innerHTML')
if ihtml == 'MOON RACER':
os.system("clear")
print("SNKR has not dropped")
time.sleep(1)
else:
print("SNKR has dropped")
pyautogui.click(1303,380)
pyautogui.hotkey('command', 't')
pyautogui.typewrite('python3 messages.py') # Notifies me by text
pyautogui.press('return')
pyautogui.click(928,248)
pyautogui.hotkey('ctrl', 'z') # Kills the bash loop
snkrs()
Bash循环文件:
#!/bin/bash
while [ 1 ]
do
python snkrs.py
done
发布于 2018-08-04 08:13:04
您正在定义一个包含chromedriver launch的方法,然后通过该方法运行一次(而不是循环),这样每次方法调用都会生成一个新的浏览器实例。与其这样做,不如做一些像这样的事情...
url = 'https://www.nike.com/launch/?s=in-stock'
driver.get(url)
# toggle grid view
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label='Show Products as List']"))).click();
# wait for shoes to drop
while not driver.find_elements((By.XPATH, "//div[@class='figcaption-content']//h3[contains(.,'MOON RACER')]"))
print("SNKR has not dropped")
time.sleep(300) // 300s = 5 mins, don't spam their site
driver.get(url)
print("SNKR has dropped")
我简化了您的代码,更改了定位器,并添加了一个循环。该脚本启动浏览器(一次),加载站点,单击网格视图切换按钮,然后查找要在此列表中显示的所需鞋子。如果shoes不存在,它只会休眠5分钟,重新加载页面,然后重试。不需要每隔1秒刷新一次页面。你会吸引人们对你自己的注意,而且你的鞋子也不会经常在网站上刷新。
发布于 2018-08-04 06:36:58
如果你只是想等待页面上的变化,那么下面的代码应该能起到作用:
snkr_has_not_dropped = True
while snkr_has_not_dropped:
elem = driver.find_element_by_xpath("//* .[ @ id = 'j_s17368440'] / div[2] / aside / div[1] / h1")
ihtml = elem.get_attribute('innerHTML')
if ihtml == 'MOON RACER':
print("SNKR has not dropped")
driver.refresh()
else:
print("SNKR has dropped")
snkr_has_not_dropped = False
只需刷新页面,然后重试。
https://stackoverflow.com/questions/51679932
复制相似问题