在selenium中如何控制滚动到底部的速度

2024-05-16 13:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习selenium,我想得到所有的示例网站的图像,图像使用lazyload,并且只有当图像的父元素出现在屏幕的可见范围内时,图像才会显示出来。在

如果图像的父元素未出现在屏幕的可见范围内,则显示以下代码:

<a class="picture" href="http://new.qq.com/omn/20190405/20190405A0CB58.html" target="_blank"><div class="lazyload-placeholder">终于出手规范融资业务!港证监会规定最高不得超过5倍融资</div></a>

如果图像的父元素出现在屏幕的可见范围内,则显示以下代码:

^{pr2}$

我想控制滚动到底部的速度,这样图像就会全部显示出来。在

如何控制在selenium中滚动到底部的速度?在

我试图修改window.scrollTo(0, document.body.scrollHeight);

但这并不成功。在

#coding:utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.by import By


driver = webdriver.Chrome()

driver.get("https://new.qq.com/rolls/?ext=news")

i = 0
while (i < 10):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(1)
    i += 1



Tags: 代码图像importdivcom元素new屏幕
1条回答
网友
1楼 · 发布于 2024-05-16 13:22:22

更新。添加了一些代码。谢谢@Sers。在

下面是一个示例,您可以如何获取新闻详细信息,如标题和img链接,检查代码内的注释:

#coding:utf-8
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.action_chains import ActionChains


driver = webdriver.Chrome()

driver.get("https://new.qq.com/rolls/?ext=news")

wait = WebDriverWait(driver, 10)


# Scroll until load more button will have "没有更多了" text
while True:
    driver.execute_script("arguments[0].scrollIntoView();",  driver.find_element_by_id("load-more"))
    if driver.find_element_by_id("load-more").text == "没有更多了":
        break

# list of maps
results = []



# Gel all news and iterate
news = wait.until(ec.presence_of_all_elements_located((By.CSS_SELECTOR, "ul.list li")))
for item in news:
    # scroll to each news
    driver.execute_script("arguments[0].scrollIntoView();", item)
    # get title
    title = item.find_element_by_css_selector("h3 a").text.strip()
    # wait until a.picture element will have visible img
    img = wait.until(ec.visibility_of(item.find_element_by_css_selector("a.picture img")))

    # add news details to the result
    results.append({"title": title, "href": item.get_attribute("href"), "img": img.get_attribute("src")})

for result in results:
    print(f"title: {result['title']}, img: {result['img']}")

driver.quit()

相关问题 更多 >