Elem无法滚动到视图中

时间:2019-03-21 00:41:23

标签: python selenium

Python和Selenium的新功能。 为了好玩,我正在抓一页。我必须先单击“评论”按钮,然后再单击“所有评论”另一个按钮,以便我可以全部获取它们。 第一次单击有效,但第二次无效。 我已经设置了硬编码滚动,但是仍然无法正常工作。

这是我正在使用的python代码:

boton = driver.find_element_by_id('tabComments_btn')
boton.click()

wait = WebDriverWait(driver, 100)

从这里开始,它不起作用(它会滚动,但显示“元素无法滚动到视图中”

driver.execute_script("window.scrollTo(0, 1300)")
botonTodos= driver.find_element_by_class_name('thread-node-children-load-all-btn')

wait = WebDriverWait(driver, 100)

botonTodos.click()

如果我只单击第一个按钮,则可以刮擦前10条评论,因此可以正常工作。

wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'thread-node-message')))

for elm in driver.find_elements_by_css_selector(".thread-node-message"):
    print(elm.text)

这是我停留在HTML中的一部分:

    <a href="#" class="thread-node-btn thread-node-children-load-next-btn">Load next 10 comments</a>
    <a href="#" class="thread-node-btn thread-node-children-load-all-btn">Load all comments</a>
    <a href="#" class="thread-node-btn thread-node-btn-post">Publicar un comentario</a>

有一个空白节点,每个节点之间带有#text标签。 任何想法欢迎。 谢谢。

1 个答案:

答案 0 :(得分:0)

以下是不同的选项。

#first create the elements ref
load_next_btn = driver.find_element_by_css_selector(".thread-node-children-load-next-btn")
load_all_btn = driver.find_element_by_css_selector(".thread-node-children-load-all-btn")
# scroll to button you are interested (I am scrolling to load_all_btn
# Option 1
load_all_btn.location_once_scrolled_into_view

# Option 2
driver.execute_script("arguments[0].scrollIntoView();",load_all_btn)

# Option 3
btnLoctation = load_all_btn.location
driver.execute_script("window.scrollTo(" + str(btnLoctation['x']) + "," + str(btnLoctation['y']) +");")

测试代码: 检查此代码是否正常工作。

url = "https://stackoverflow.com/questions/55228646/python-selenium-cant-sometimes-scroll-element-into-view/55228932?    noredirect=1#comment97192621_55228932"
driver.get(url)
element = driver.find_element_by_xpath("//a[.='Contact Us']")
element.location_once_scrolled_into_view
time.sleep(1)
driver.find_element_by_xpath("//p[.='active']").location_once_scrolled_into_view
driver.execute_script("arguments[0].scrollIntoView();",element)

time.sleep(1)