В настоящее время я использую selenium webdriver для анализа страницы друзей пользователя facebook и извлечения всех идентификаторов из AJAX script. Но мне нужно прокрутить вниз, чтобы получить всех друзей. Как я могу прокрутить вниз в Селене. Я использую python.
Как прокручивать веб-страницу с помощью selenium webdriver в 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
Ссылка: fooobar.com/questions/45151/...
Ответ 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 секунды.