Python-Selenium-WebDriver页面滚动过去元素而不“点击”它们即使驱动程序应该是

问题描述 投票:1回答:2

我正在开发一个项目,在Firefox中使用Python和Selenium WebDriver,以便打开Goog​​le,搜索特定项目,然后让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
python selenium selenium-webdriver python-requests python-3.7
2个回答
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

0
投票

循环中的最后一行,

idx + = 1

语法不正确。它应该是idx += 1而不是。所以我不知道你是如何摆脱循环的,它会继续与idx = 0迭代,我错过了什么?

© www.soinside.com 2019 - 2024. All rights reserved.