python - Elem 无法滚动到视图中
问题描述
python 和 selenium 的新手。为了好玩,我正在刮一页。我必须单击第一个按钮查看评论,然后单击另一个按钮查看所有评论,这样我才能获得所有评论。第一次点击有效,但第二次无效。我已经设置了一个硬编码的滚动条,但仍然无法正常工作。
这是我正在处理的python代码:
boton = driver.find_element_by_id('tabComments_btn')
boton.click()
wait = WebDriverWait(driver, 100)
从这里开始,它不起作用(它滚动但它说'elem不能滚动到视图中'
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 的空白节点。欢迎任何想法。谢谢。
解决方案
以下是不同的选项。
#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)
时间.sleep(1)
推荐阅读
- python - Pyspark 中的 Pandas Udf 在纱线客户端或集群模式下仅在 1 个执行程序中运行
- docker - 来自其他实例和本地 PC 的 docker swarm join 连接错误
- python - 如何在 Python 中从对象中获取数据
- python - Django ORM 使用开始限制限制查询集
- apache-kafka - 如何仅处理来自 kafkaStreams 的唯一键?
- java - 当值在变量中时,Java使用replaceAll替换大括号字符串,java 8
- c# - MapWhen Notworking 所有路线
- php - 如何使用 docker-php-extension-installer 安装扩展
- python - socket.bind() 与 socket.listen()
- assembly - 更改退货地址 AT&T 大会