如何使用selenium python向下滚动谷歌Map

rqcrx0a6  于 2023-03-07  发布在  Python
关注(0)|答案(4)|浏览(209)

我正试图使用 selenium 向下滚动谷歌Map页面,但无法做到这一点。我已经尝试了所有的东西写在这里:Scroll down google maps webpage using selenium python
下面是我的代码:

def scroll(self):        
    SCROLL_PAUSE_TIME = 5

    # Get scroll height
    last_height = self.execute_script("return document.body.scrollHeight") 

    number = 0

    while True:
        number = number+1

        # Scroll down to bottom
        
        ele = self.find_element_by_css_selector('div[jstcache="211"]')
        print(ele)
        self.execute_script('arguments[0].scrollBy(0, 500)', ele)

        # Wait to load page

        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        print(f'last height: {last_height}')

        ele = self.find_element_by_css_selector('div[jstcache="211"]')
        
        new_height = self.execute_script("return arguments[0].scrollHeight", ele) 

        print(f'new height: {new_height}')

        if number == 5:
            break

        if new_height == last_height:
            break

        print('cont')
        last_height = new_height

但是不能知道如何向下滚动。
好心帮忙!!

xwmevbvl

xwmevbvl1#

对我有效的解决方案是:

def scroll(self):
    for i in range(6,25,3): 
        last_review = self.find_elements_by_css_selector('div[jstcache="192"]')
        self.execute_script('arguments[0].scrollIntoView(true);', last_review[i])
        time.sleep(5)

这背后的想法是,每次获取所有业务框并滚动到最后一个视图,然后等待,再次获取,再次滚动到最后一个视图,依此类推。

r55awzrz

r55awzrz2#

当你进入站点后,你很可能会打开侧面板。通过点击屏幕中心关闭它。然后发送箭头键到Map元素。

from selenium.webdriver.common.keys import Keys

driver.find_element(BY.CLASS, "dmCR2e widget-scene").click()
driver.find_element(BY.CLASS, "dmCR2e widget-scene").send_keys(Keys.ARROW_DOWN) 

#ARROW_UP ARROW_RIGHT ARROW_LEFT
c0vxltue

c0vxltue3#

我使用了相同的代码,您可以通过删除以下行来修复它:)

if number == 5:
    break
h7wcgrx3

h7wcgrx34#

其他的答案对我不起作用,所以这是我想到的。

divSideBar=driver.find_element(By.CSS_SELECTOR,f"div[aria-label='Results for {query}']")

keepScrolling=True
while(keepScrolling):
    divSideBar.send_keys(Keys.PAGE_DOWN)
    time.sleep(0.5)
    divSideBar.send_keys(Keys.PAGE_DOWN)
    time.sleep(0.5)
    html =driver.find_element(By.TAG_NAME, "html").get_attribute('outerHTML')
    if(html.find("You've reached the end of the list.")!=-1):
        keepScrolling=False

“query”只是您的搜索查询,如屏幕截图here所示。

相关问题