繁体   English   中英

Python-硒通过数组

[英]Python - Selenium going through array

我想做自动脚本。 我在程序开始时定义了一个数组。 以后的程序打开浏览器并在google中搜索某个特定的单词(例如apple),下一个程序从数组中首先单击字符串并关闭浏览器。 稍后执行相同的操作,但是它将单击数组中单词的秒。 我的代码:

 from selenium import webdriver
from selenium.webdriver.common.keys import Keys


driver = webdriver.Chrome("C:/Users/Daniel/Desktop/chromedriver.exe")
driver.implicitly_wait(30)
driver.maximize_window()




hasla = ["ispot","myapple"]

for slogan in hasla:
    driver.get("http://www.google.com")
    search_field = driver.find_element_by_id("lst-ib")

    search_field.clear()
    search_field.send_keys("apple")
    search_field.submit()
    name = driver.find_element_by_link_text(slogan)
    name.click()
    driver.quit()
    driver.implicitly_wait(10)

当我从Windows中的控制台启动此程序时。 程序正在打开浏览器,在ispot和clsoe浏览器中寻找苹果点击,但是它没有打开新的浏览器,并且它对数组中的下一个字符串没有做同样的事情。 有什么办法吗?

在控制台中,我有这个: 屏幕

您正在for循环中退出浏览器,因此第二次迭代无法执行任何操作,因为没有打开浏览器。 如果您需要每次都重新启动,则可以尝试打开一个新标签并关闭旧标签。 尝试这个:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome("C:/Users/Daniel/Desktop/chromedriver.exe")
driver.implicitly_wait(30)
driver.maximize_window()

hasla = ["ispot","myapple"]

for slogan in hasla:
    driver.get("http://www.google.com")
    search_field = driver.find_element_by_id("lst-ib")

    search_field.clear()
    search_field.send_keys("apple")
    search_field.submit()
    name = driver.find_element_by_link_text(slogan)
    name.click()

    # Save the current tab id
    old_handle = driver.current_window_handle

    # Execute JavaScript to open a new tab and save its id
    driver.execute_script("window.open('');")
    new_handle = driver.window_handles[-1]

    # Switch to the old tab and close it
    driver.switch_to.window(old_handle)
    driver.close()

    # Switch focus to the new tab
    driver.switch_to.window(new_handle)

如果您要关闭标签,则将无法看到结果。 您可能需要保持打开状态,然后转到新标签页。 在这种情况下,只需删除driver.close()

另外,如果您确实想每次都完全关闭浏览器并重新打开,则只需在for循环中包含前三行。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

hasla = ["ispot","myapple"]

for slogan in hasla:
    driver = webdriver.Chrome("C:/Users/Daniel/Desktop/chromedriver.exe")
    driver.implicitly_wait(30)
    driver.maximize_window()

    driver.get("http://www.google.com")
    search_field = driver.find_element_by_id("lst-ib")

    search_field.clear()
    search_field.send_keys("apple")
    search_field.submit()
    name = driver.find_element_by_link_text(slogan)
    name.click()
    driver.quit()

要回答第二个问题:

首先,导入NoSuchElementException:

from selenium.common.exceptions import NoSuchElementException

然后,将您的try / except替换为:

    try:
        name = driver.find_element_by_link_text(slogan)
        name.click()
    except NoSuchElementException:
        print('No such element')
    driver.quit()

无论是否找到该元素,它仍将关闭浏览器并转到下一个迭代。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM