Как прокручивать веб-страницу с помощью selenium webdriver в python?
В настоящее время я использую selenium webdriver для анализа страницы друзей пользователя facebook и извлечения всех идентификаторов из AJAX script. Но мне нужно прокрутить вниз, чтобы получить всех друзей. Как я могу прокрутить вниз в Селене. Я использую python.
ОТВЕТЫ
Ответ 1
Вы можете использовать
driver.execute_script("window.scrollTo(0, Y)")
где Y — высота (на fullhd мониторе это 1080). (Спасибо @lukeis)
Вы также можете использовать
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
для прокрутки до нижней части страницы.
Если вы хотите прокрутить страницу с бесконечной загрузкой, например, из социальных сетей, Facebook и т.д. (Благодаря @Cuong Tran)
SCROLL_PAUSE_TIME = 0.5 # Get scroll height last_height = driver.execute_script("return document.body.scrollHeight") while True: # Scroll down to bottom driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height
Ответ 2
Если вы хотите прокрутить вниз до бесконечной страницы (например, linkedin.com), вы можете использовать этот код:
SCROLL_PAUSE_TIME = 0.5 # Get scroll height last_height = driver.execute_script("return document.body.scrollHeight") while True: # Scroll down to bottom driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height
Ответ 3
тот же метод, что показано здесь:
в python вы можете просто использовать
driver.execute_script("window.scrollTo(0, Y)")
(Y — это вертикальное положение, которое вы хотите прокрутить)
Ответ 4
from selenium.webdriver.common.keys import Keys html = browser.find_element_by_tag_name('html') html.send_keys(Keys.END)
Ответ 5
element=find_element_by_xpath("xpath of the li you are trying to access") element.location_once_scrolled_into_view
Это помогло, когда я пытался получить доступ к «li», который не был виден.
Ответ 6
Для моей цели я хотел прокрутить вниз, помня о положении окон. Мое решение было похоже и использовал window.scrollY
driver.execute_script("window.scrollTo(0, window.scrollY + 200)")
который перейдет в текущую позицию прокрутки у + 200
Ответ 7
Вот как вы прокручиваете страницу вниз:
driver.execute_script("window.scrollTo(0, 1000);")
Ответ 8
Ни один из этих ответов не работал у меня, по крайней мере, не для прокрутки страницы результатов поиска в facebook, но я нашел после большого тестирования этого решения:
while driver.find_element_by_tag_name('div'): driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") Divs=driver.find_element_by_tag_name('div').text if 'End of Results' in Divs: print 'end' break else: continue
Ответ 9
Самым простым способом, который я нашел для решения этой проблемы, было выбрать ярлык и затем отправить:
label.sendKeys(Keys.PAGE_DOWN);
Ответ 10
При работе с YouTube плавающие элементы дают значение «0» в качестве высоты прокрутки, поэтому вместо использования «return document.body.scrollHeight» попробуйте с помощью этого «return document.documentElement.scrollHeight» настроить время паузы прокрутки в соответствии с вашим Интернетом. Скорость, иначе он будет работать только один раз, а затем сломается после этого.
SCROLL_PAUSE_TIME = 1 # Get scroll height """last_height = driver.execute_script("return document.body.scrollHeight") this dowsnt work due to floating web elements on youtube """ last_height = driver.execute_script("return document.documentElement.scrollHeight") while True: # Scroll down to bottom driver.execute_script("window.scrollTo(0,document.documentElement.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.documentElement.scrollHeight") if new_height == last_height: print("break") break last_height = new_height
Ответ 11
Я искал способ прокрутки динамической веб-страницы и автоматически останавливался, как только был достигнут конец страницы, и нашел эту ветку.
Пост @Cuong Tran, с одной основной модификацией, был ответом, который я искал. Я подумал, что другие могут посчитать эту модификацию полезной (она сильно влияет на работу кода), поэтому этот пост.
Модификация заключается в перемещении оператора, который фиксирует высоту последней страницы внутри цикла (чтобы каждая проверка сравнивалась с высотой предыдущей страницы).
Непрерывно прокручивает динамическую веб-страницу ( .scrollTo() ), останавливаясь только тогда, когда за одну итерацию высота страницы остается неизменной.
(Существует другая модификация, где оператор break находится внутри другого условия (в случае, если страница «залипает»), которое можно удалить).
SCROLL_PAUSE_TIME = 0.5 while True: # Get scroll height ### This is the difference. Moving this *inside* the loop ### means that it checks if scrollTo is still scrolling last_height = driver.execute_script("return document.body.scrollHeight") # Scroll down to bottom driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: # try again (can be removed) driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Wait to load page time.sleep(SCROLL_PAUSE_TIME) # Calculate new scroll height and compare with last scroll height new_height = driver.execute_script("return document.body.scrollHeight") # check if the page height has remained the same if new_height == last_height: # if so, you are done break # if not, move on to the next loop else: last_height = new_height continue
Ответ 12
прокрутка загрузки страниц. Пример: средний, квора и т.д.
last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight-1000);") # Wait to load the page. driver.implicitly_wait(30) # seconds new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height # sleep for 30s driver.implicitly_wait(30) # seconds driver.quit()
Ответ 13
Этот код прокручивается до конца, но не требует, чтобы вы каждый раз ждали. Он будет постоянно прокручиваться, а затем останавливаться на дне (или время ожидания)
from selenium import webdriver import time driver = webdriver.Chrome(executable_path='chromedriver.exe') driver.get('https://example.com') pre_scroll_height = driver.execute_script('return document.body.scrollHeight;') run_time, max_run_time = 0, 1 while True: iteration_start = time.time() # Scroll webpage, the 100 allows for a more 'aggressive' scroll driver.execute_script('window.scrollTo(0, 100*document.body.scrollHeight);') post_scroll_height = driver.execute_script('return document.body.scrollHeight;') scrolled = post_scroll_height != pre_scroll_height timed_out = run_time >= max_run_time if scrolled: run_time = 0 pre_scroll_height = post_scroll_height elif not scrolled and not timed_out: run_time += time.time() - iteration_start elif not scrolled and timed_out: break # closing the driver is optional driver.close()
Это намного быстрее, чем ждать 0,5-3 секунды каждый раз, когда ответ может занять 0,1 секунды.
selenium-webdriver
Скроллинг
Различные прокрутки с использованием java разными способами
Ниже дать решение можно также использовать в других поддерживаемых языках программирования с некоторыми изменениями синтаксиса
- Выполнение Прокрутка вниз по страницам / разделу / разделению на веб-странице, в то время как есть настраиваемая полоса прокрутки (не прокрутка браузера). Нажмите здесь. Для демонстрации и проверки полосы прокрутки имеет свой независимый элемент.
В приведенном ниже коде передайте элемент полосы прокрутки и укажите точки прокрутки.
public static boolean scroll_Page(WebElement webelement, int scrollPoints) < try < System.out.println("---------------- Started - scroll_Page ----------------"); driver = ExecutionSetup.getDriver(); dragger = new Actions(driver); // drag downwards int numberOfPixelsToDragTheScrollbarDown = 10; for (int i = 10; i < scrollPoints; i = i + numberOfPixelsToDragTheScrollbarDown) < dragger.moveToElement(webelement).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release(webelement).build().perform(); >Thread.sleep(500); System.out.println("---------------- Ending - scroll_Page ----------------"); return true; > catch (Exception e) < System.out.println("---------------- scroll is unsucessfully done in scroll_Page ----------------"); e.printStackTrace(); return false; >>
- Выполнение прокрутки вверх страницы / раздела / деления на веб-странице, пока есть пользовательская полоса прокрутки (не прокрутка браузера). Нажмите здесь. Для демонстрации и проверки полосы прокрутки имеет свой независимый элемент.
В приведенном ниже коде передайте элемент полосы прокрутки и укажите точки прокрутки.
public static boolean scroll_Page_Up(WebElement webelement, int scrollPoints) < try < System.out.println("---------------- Started - scroll_Page_Up ----------------"); driver = ExecutionSetup.getDriver(); dragger = new Actions(driver); // drag upwards int numberOfPixelsToDragTheScrollbarUp = -10; for (int i = scrollPoints; i >10; i = i + numberOfPixelsToDragTheScrollbarUp) < dragger.moveToElement(webelement).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarUp).release(webelement).build().perform(); >System.out.println("---------------- Ending - scroll_Page_Up ----------------"); return true; > catch (Exception e) < System.out.println("---------------- scroll is unsucessfully done in scroll_Page_Up----------------"); e.printStackTrace(); return false; >>
- Чтобы выполнить прокрутку вниз, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокрутить вниз с помощью клавиши «Вниз» . Нажмите здесь для демонстрации
В приведенном ниже коде передайте свой элемент области прокрутки, например и нажмите кнопку «вниз».
public static boolean pageDown_New(WebElement webeScrollArea, int iLoopCount) < try < System.out.println("---------------- Started - pageDown_New ----------------"); driver = ExecutionSetup.getDriver(); dragger = new Actions(driver); for (int i = 0; i System.out.println"---------------- Ending - pageDown_New ----------------"); return true; > catch (Exception e) < System.out.println("---------------- Not able to do page down ----------------"); return false; >>
- Чтобы выполнить прокрутку вверх, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокрутить вверх с помощью клавиши UP UP . Нажмите здесь для демонстрации
В нижеприведенном коде передайте свой элемент области прокрутки, например и нажмите клавишу вверх.
public static boolean pageUp_New(WebElement webeScrollArea, int iLoopCount) < try < System.out.println("---------------- Started - pageUp_New ----------------"); driver = ExecutionSetup.getDriver(); dragger = new Actions(driver); for (int i = 0; i System.out.println("---------------- Ending - pageUp_New ----------------"); return true; > catch (Exception e) < System.out.println("---------------- Not able to do page up ----------------"); return false; >>
- Чтобы выполнить прокрутку вниз, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокрутить вниз с помощью клавиши «Только стрелка вниз» . Нажмите здесь для демонстрации
В приведенном ниже коде передайте свой элемент области прокрутки, например и нажмите клавишу «вниз».
public static boolean scrollDown_Keys(WebElement webeScrollArea, int iLoopCount) < try < System.out.println("---------------- Started - scrollDown_Keys ----------------"); driver = ExecutionSetup.getDriver(); dragger = new Actions(driver); for (int i = 0; i System.out.println("---------------- Ending - scrollDown_Keys ----------------"); return true; > catch (Exception e) < System.out.println("---------------- Not able to do scroll down with keys----------------"); return false; >>
- Чтобы выполнить прокрутку вверх, когда несколько прокрутки браузера (Встроенный браузер), и вы хотите прокручивать вверх с помощью клавиши «Только стрелка вверх» . Нажмите здесь для демонстрации
В приведенном ниже коде передайте свой элемент области прокрутки, например и введите требуемый ключ.
public static boolean scrollUp_Keys(WebElement webeScrollArea, int iLoopCount) < try < System.out.println("---------------- Started - scrollUp_Keys ----------------"); driver = ExecutionSetup.getDriver(); dragger = new Actions(driver); for (int i = 0; i System.out.println("---------------- Ending - scrollUp_Keys ----------------"); return true; > catch (Exception e) < System.out.println("---------------- Not able to do scroll up with keys----------------"); return false; >>
- Чтобы выполнить прокрутку вверх / вниз при прокрутке браузера (встроенный браузер), и вы хотите прокручивать вверх / вниз только с фиксированной точкой . Нажмите здесь для демонстрации
В приведенном ниже коде передайте свою точку прокрутки. Положительное означает, что вниз и отрицательные средства прокручиваются вверх.
public static boolean scroll_without_WebE(int scrollPoint) < JavascriptExecutor jse; try < System.out.println("---------------- Started - scroll_without_WebE ----------------"); driver = ExecutionSetup.getDriver(); jse = (JavascriptExecutor) driver; jse.executeScript("window.scrollBy(0," + scrollPoint + ")", ""); System.out.println("---------------- Ending - scroll_without_WebE ----------------"); return true; >catch (Exception e) < System.out.println("---------------- scroll is unsucessful in scroll_without_WebE ----------------"); e.printStackTrace(); return false; >>
- Чтобы выполнить прокрутку вверх / вниз при прокрутке браузера (встроенный браузер), и вы хотите прокручивать вверх / вниз, чтобы сделать элемент в видимой области или динамическом прокрутке . Нажмите здесь для демонстрации
В приведенном ниже коде передайте свой элемент.
public static boolean scroll_to_WebE(WebElement webe) < try < System.out.println("---------------- Started - scroll_to_WebE ----------------"); driver = ExecutionSetup.getDriver(); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", webe); System.out.println("---------------- Ending - scroll_to_WebE ----------------"); return true; >catch (Exception e) < System.out.println("---------------- scroll is unsucessful in scroll_to_WebE ----------------"); e.printStackTrace(); return false; >>
Примечание. Пожалуйста, проверьте свой случай и используйте методы. Если какой-либо случай отсутствует, дайте мне знать.