驱动程序进入循环重复打开 chrome
Driver get within loop repeats opening chrome
如何在获取数据时减少 selenium 运行 google chrome 的数量。准确地说,我有这段代码,其中迭代了 200 多次:
try:
DRIVER_PATH = '/home/Selenium-drivers/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get(url_specific_wine)
regions = driver.find_element(By.XPATH, '//*[@id="MainContent"]/div[2]/div[4]/div/div/div[5]/div[4]/div/div/div[9]/div[2]').text
except:
regions = ''
all_regions.append(regions)
每次都会打开一个google chrome。如何避免这种情况?
您当前的代码至少可以改进 2 点:
1.
DRIVER_PATH = '/home/Selenium-drivers/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
应该退出循环。
2.
您应该使用 Expected Conditions 显式等待,如下所示:
DRIVER_PATH = '/home/Selenium-drivers/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
wait = WebDriverWait(driver, 20)
try:
driver.get(url_specific_wine)
regions = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="MainContent"]/div[2]/div[4]/div/div/div[5]/div[4]/div/div/div[9]/div[2]'))).text
except:
regions = ''
all_regions.append(regions)
//*[@id="MainContent"]/div[2]/div[4]/div/div/div[5]/div[4]/div/div/div[9]/div[2]
XPath 定位器似乎不可靠。我不知道你想定位什么元素,这里的定位器必须改进。
为了使用上面的 wait
对象,您将需要以下导入
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
如何在获取数据时减少 selenium 运行 google chrome 的数量。准确地说,我有这段代码,其中迭代了 200 多次:
try:
DRIVER_PATH = '/home/Selenium-drivers/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get(url_specific_wine)
regions = driver.find_element(By.XPATH, '//*[@id="MainContent"]/div[2]/div[4]/div/div/div[5]/div[4]/div/div/div[9]/div[2]').text
except:
regions = ''
all_regions.append(regions)
每次都会打开一个google chrome。如何避免这种情况?
您当前的代码至少可以改进 2 点:
1.
DRIVER_PATH = '/home/Selenium-drivers/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
应该退出循环。
2.
您应该使用 Expected Conditions 显式等待,如下所示:
DRIVER_PATH = '/home/Selenium-drivers/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
wait = WebDriverWait(driver, 20)
try:
driver.get(url_specific_wine)
regions = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="MainContent"]/div[2]/div[4]/div/div/div[5]/div[4]/div/div/div[9]/div[2]'))).text
except:
regions = ''
all_regions.append(regions)
//*[@id="MainContent"]/div[2]/div[4]/div/div/div[5]/div[4]/div/div/div[9]/div[2]
XPath 定位器似乎不可靠。我不知道你想定位什么元素,这里的定位器必须改进。
为了使用上面的 wait
对象,您将需要以下导入
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC