注意,目前的实战都是流水账式写的,后面才会结合框架+PO模式
目的是为了掌握所学的Selenium基础

实战题目

  1. 访问: https://www.vmall.com/
  2. 获取一级菜单下包含哪些二级菜单,不包含查看全部
  3. 然后获取下面,热销单品中所有 顶部 带有 爆款字样的产品名称及价格

Selenium系列(19) - Web UI 自动化基础实战(6) - 图1
Selenium系列(19) - Web UI 自动化基础实战(6) - 图2

代码思路(人为测试时的操作步骤)

  1. 定位一级菜单的选项列表
  2. 循环列表,每次都将鼠标悬浮在当前选项上,然后打印二级菜单的列表
  3. 热销单品在页面下方,需要滑动页面
  4. 定位热销单品列表
  5. 循环,获取标题和价格,打印爆款

代码

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. __title__ =
  5. __Time__ = 2020/4/2 20:04
  6. __Author__ = 小菠萝测试笔记
  7. __Blog__ = https://www.cnblogs.com/poloyy/
  8. """
  9. from time import sleep
  10. from selenium import webdriver
  11. from selenium.webdriver.common.by import By
  12. from selenium.webdriver.support import expected_conditions as ec
  13. from selenium.webdriver.support.wait import WebDriverWait
  14. from selenium.webdriver.common.action_chains import ActionChains
  15. driver = webdriver.Chrome("../resources/chromedriver.exe")
  16. action = ActionChains(driver)
  17. def wait_element(by_, element_):
  18. element = WebDriverWait(driver, timeout=10).until(
  19. ec.presence_of_element_located((by_, element_))
  20. )
  21. return element
  22. def wait_elements(by_, element_):
  23. element = WebDriverWait(driver, timeout=10).until(
  24. ec.presence_of_all_elements_located((by_, element_))
  25. )
  26. return element
  27. # 打开网站
  28. driver.get("https://www.vmall.com/")
  29. # 列表
  30. lists = wait_elements(By.XPATH, '//div[@id="category-block"]/div/ol/li')
  31. for one in lists:
  32. one_v = one.find_element_by_xpath("./input[2]").get_attribute("value")
  33. print(f"一级菜单:{one_v}")
  34. # hover
  35. action.move_to_element(one).perform()
  36. # hover出来的面板
  37. items = one.find_elements_by_xpath('./div[contains(@class,"category-panels")]/ul/li[@class="subcate-item"]')
  38. for item in items:
  39. value = item.find_element_by_xpath('./input[1]').get_attribute("value")
  40. print(f"\t{value}")
  41. # 往下滚动1000px
  42. js = "document.documentElement.scrollTop = 1000"
  43. driver.execute_script(js)
  44. # 打印爆款
  45. hot_lists = driver.find_elements_by_xpath(
  46. '//div[contains(@class,"home-hot-goods")]//ul[@class="grid-list clearfix"]/li')
  47. for hot in hot_lists:
  48. title = hot.find_element_by_xpath('./a/div[@class="grid-title"]')
  49. price = hot.find_element_by_xpath('./a/p[@class="grid-price"]')
  50. print(f"爆款:{title.text}, 价格:{price.text}")
  51. sleep(5)
  52. driver.quit()

转载: https://www.cnblogs.com/poloyy/p/12632293.html