首页 > 解决方案 > 如何滚动几次以找到一个元素?

问题描述

我想创建一个脚本来保持滚动,直到找到所需的元素:

from appium.webdriver.common.touch_action import TouchAction

该页面是具有不同游戏标题的事件页面。

到目前为止,我得到的只是单次滚动:

# swipe down
time.sleep(1)
print('Scrolling the page..')
time.sleep(4)
touch = TouchAction(driver)
touch.long_press(x=500, y=1800).move_to(x=500, y=400).release().perform()
time.sleep(2)
print('PASS - Step 1. Page was scrolled')

使用以下方法搜索元素:

selenium.webdriver.support import expected_conditions as EC
# Game name
time.sleep(1)
wait = WebDriverWait(driver, 15)
Event_Name = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@text="Event name"]//ancestor::*[contains(@class, "android.widget.LinearLayout")]')))
Event_Name.click()
time.sleep(2)
Game_title = driver.find_element_by_id('com.project.projectname:id/eventName')
print('PASS - Step 2. ' + Game_title.text + ' game card was clicked')
time.sleep(2)
wait = WebDriverWait(driver, 15)
Game_size_GameName = wait.until(EC.visibility_of_all_elements_located((By.ID, 'com.project.projectname:id/size')))
# noinspection PyTypeChecker
for size in Game_size_Gamename:
    if '55.68 MB' == size.text:
        print('PASS - Step 3. User is on the ' + Game_title.text + ' product page')
    else:
        print('FAIL - Step 3. Failed to redirect user')
time.sleep(2)
Events_tab_title = wait.until(EC.visibility_of_element_located((By.ID, 'com.project.projectname:id/screenTitle')))
back_button.click()
print('PASS - Step 11. User is back on the ' + Events_tab_title.text + ' tab')
time.sleep(2)

任何人都可以帮助我吗?提前致谢。

提及:并非所有元素都是可见的,这就是我需要在脚本中滚动页面的原因。

标签: pythonandroidseleniumtouch-eventappium-android

解决方案


我尝试了几种将网页滚动到元素的方法。其中一些工作但向下滚动页面到我需要的元素上方的位置。最好的工作是 JavaScript 的:

element = driver.find_element_by_id('element_id')
context.driver.execute_script("arguments[0].scrollIntoView();", element)
element.click()

推荐阅读