我正在开发一个项目,在Firefox中使用Python和Selenium WebDriver,以便打开Google,搜索特定项目,然后让Selenium在不同的标签中打开前5个搜索结果。
我想通过使用硒复制Ctrl Button Down-->Click Link-->Ctrl Button Up
来做到这一点。我在编写“Click
动作时遇到的问题是,这些元素不在ViewPort中,因此无法点击。所以我添加了Move_to_Element操作并且问题仍然存在(但是它打开了第一个2或3个链接)。然后我使用元素的位置作为参考添加了window.scroll_to
脚本,但现在它没有打开任何链接。浏览器打开,它只是在链接后滚动链接,直到它到达最后一个。
你可以帮我弄清楚我在这里做错了什么,因为逻辑似乎很好,并且在添加scroll_to
动作之前它起作用(至少对于前2-3个链接)。
非常感谢
#TO-DO open google
browser = webdriver.Firefox()
browser.get("https://www.google.com")
#Selecting the search bar and send search text
searchElem = browser.find_element_by_css_selector('.gLFyf')
searchElem.send_keys("cars")
searchElem.submit()
time.sleep(5)
last_height = browser.execute_script("return document.body.scrollHeight")
# browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
found_elems=browser.find_elements_by_class_name('LC20lb')
#Selecting and clicking on first 5 pages
idx = 0
while idx <= min(len(found_elems),5):
found_elem = found_elems[idx]
#Find the height of the element
ht = found_elem.location['y']
print("Opening up ",found_elem.text)#Page Name
try:
print("In try block")
#Scrolling to the element
browser.execute_script("window.scrollTo(0, {});".format(ht))
#Setting up Action Chains to move to elem-> Click on the links #with ctrl key down so as to open them in different tabs
ActionChains(browser)\
.move_to_element(found_elem)\
.key_down(Keys.CONTROL) \
.click(found_elem) \
.key_up(Keys.CONTROL) \
.perform()
print("Browser moved to "+str(ht))
print("Exiting try")
except Exception as e:
print("In exception")
print(e)
break
idx + = 1
如果您打算在新标签页中打开搜索链接。那么这是简化的代码。
browser.get("https://www.google.com")
#Selecting the search bar and send search text
searchElem = browser.find_element_by_css_selector('.gLFyf')
searchElem.send_keys("cars")
searchElem.submit()
time.sleep(5)
found_elems=browser.find_elements_by_xpath("//*[@class='LC20lb']/parent::a")
#Selecting and clicking on first 5 pages
idx = 0
while idx <= min(len(found_elems),5):
found_elem = found_elems[idx]
# scroll to link
found_elem.location_once_scrolled_into_view
print("Opening up ",found_elem.text)#Page Name
try:
# opening the link in new tab
browser.execute_script("window.open('"+found_elem.get_attribute('href')+"')")
except Exception as e:
print(e)
break
idx =idx+1
循环中的最后一行,
idx + = 1
语法不正确。它应该是idx += 1
而不是。所以我不知道你是如何摆脱循环的,它会继续与idx = 0
迭代,我错过了什么?