Python-Selenium-WebDriver即使驱动程序应该滚动页面,这些页面仍在滚动元素而没有“点击”它们

时间:2019-03-27 03:00:29

标签: python selenium selenium-webdriver python-requests python-3.7

我正在一个项目中,在Firefox中使用Python和Selenium WebDriver,以便打开Goog​​le,搜索特定项目,然后让Selenium在不同选项卡中打开前5个搜索结果。

我想通过使用硒复制Ctrl Button Down-->Click Link-->Ctrl Button Up来做到这一点。我在编写“ Click”操作时遇到的问题是元素不在ViewPort中,因此无法单击。因此,我添加了Move_to_Element操作,问题仍然存在(但必须先打开2或3 LINKS。),然后我以元素的位置作为参考添加了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

2 个答案:

答案 0 :(得分:0)

循环的最后一行,

idx + = 1

语法不正确。应该改为idx += 1。因此,我看不到您会如何跳出循环,它只会不断地重复idx = 0,我会丢失什么吗?

答案 1 :(得分:0)

如果您打算在新标签页中打开搜索链接。然后是简化的代码。

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