100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > python+selenium 采集动态加载(下拉加载)的页面内容

python+selenium 采集动态加载(下拉加载)的页面内容

时间:2023-09-29 22:04:45

相关推荐

python+selenium 采集动态加载(下拉加载)的页面内容

python+selenium 采集动态加载(下拉加载)的页面内容

软件版本:

python 3.7.2

selenium 3.141.0

pycharm .3.5

具体实现代码如下:

from selenium import webdriverfrom selenium.webdriver.chrome.options import Optionsimport time# 创建chrome浏览器驱动,无头模式chrome_options = Options()# chrome_options.add_argument('--headless')chrome_options.add_argument("--start-maximized");driver = webdriver.Chrome("D://googleDever//chromedriver.exe",chrome_options=chrome_options)# 加载界面driver.get("/search?keyword=china")time.sleep(3)# 获取页面初始高度js = "return action=document.body.scrollHeight"height = driver.execute_script(js)# 将滚动条调整至页面底部driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')time.sleep(5)#定义初始时间戳(秒)t1 = int(time.time())#定义循环标识,用于终止while循环status = True# 重试次数num=0while status:# 获取当前时间戳(秒)t2 = int(time.time())# 判断时间初始时间戳和当前时间戳相差是否大于30秒,小于30秒则下拉滚动条if t2-t1 < 30:new_height = driver.execute_script(js)if new_height > height :time.sleep(1)driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')# 重置初始页面高度height = new_height# 重置初始时间戳,重新计时t1 = int(time.time())elif num < 3: # 当超过30秒页面高度仍然没有更新时,进入重试逻辑,重试3次,每次等待30秒time.sleep(3)num = num+1else: # 超时并超过重试次数,程序结束跳出循环,并认为页面已经加载完毕!print("滚动条已经处于页面最下方!")status = False# 滚动条调整至页面顶部driver.execute_script('window.scrollTo(0, 0)')break# 打印页面源码content = driver.page_sourceprint(content)

以上代码为selenium采集动态下拉加载页面,使用上述代码执行后,可通过其他方式进行页面元素获取!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。