首页 > 解决方案 > 使用 Selenium+Python 在 Chome 中打开新选项卡和搜索

问题描述

Python3/Windows10/PyCharm/Selenium/Chrome

您好,我正在尝试在 chrome 中打开一个选项卡,导航到 bing,搜索一个术语,打开一个新选项卡,导航到 bing,然后搜索另一个术语。

  1. 这适用于前三个搜索词,但我在搜索词 4 上遇到索引错误。
  2. 搜索词 3 在 chrome 的“弹出选项卡”中打开,但会搜索。
  3. 搜索词 4 在 chrome 的“弹出选项卡”中打开,但出现错误。
  4. driver.implicitly_wait(3) 似乎没有工作或减慢程序的速度。

我有数百个搜索词保存在一个 excel 文件中,我正在尝试从该电子表格中自动搜索(分组),但我担心我的代码可能无法扩展到那个。

任何意见是极大的赞赏:)

print ("Hello, world!")
from selenium import webdriver
import time

driverwebdriver.Chrome(r"C:\Users")

#search term 1 denver broncos
#this opens chrome, navigates to bing, searches for "denver broncos"
driver.get("https://bing.com/")
driver.find_element_by_name("q").send_keys("denver broncos")
driver.find_element_by_name("go").click()
driver.switch_to.window(driver.window_handles[0])
#driver.implicitly_wait(3)

#search term 2 mad men
#this creates a new tab
driver.execute_script("window.open('https://www.bing.com', 'new window')")
driver.switch_to.window(driver.window_handles[1])
#driver.execute_script("window.open('https://bing.com/')")
driver.find_element_by_name("q").send_keys("mad men")
driver.find_element_by_name("go").click()
#driver.implicitly_wait(3)

#search term 3 old enlish sheepdog
#this creates a new "pop out tab", and searches for "old englsh sheepdog"
driver.execute_script("window.open('https://www.bing.com',
'https://www.bing.com', 'new window')")
driver.switch_to.window(driver.window_handles[2])
driver.find_element_by_name("q").send_keys("old english sheepdog")
driver.find_element_by_name("go").click()
#driver.implicitly_wait(3)

#search term 4 phish fall 97 tour
# this gets this error code
driver.execute_script("window.open('https://www.bing.com',
'https://www.bing.com','https://www.bing.com', 'new window')")
driver.switch_to.window(driver.window_handles[3])
driver.find_element_by_name("q").send_keys("phish fall 97 tour")
drive r.find_element_by_name("go").click()
#driver.implicitly_wait(3)

print("Code Complete!")

感谢您的帮助,我是全新的:)

标签: windowsgoogle-chromeselenium-webdriverpycharm

解决方案


推荐阅读