案例:动态页面模拟点击
# -*- coding:utf-8 -*- # python的测试模块 import unittest from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options from bs4 import BeautifulSoup class douyuSelenium(unittest.TestCase): # 初始化方法 def setUp(self): options = Options() options.add_argument('-headless') self.driver = Firefox(executable_path='/Users/loaderman/Documents/geckodriver', firefox_options=options) self.num = 0 self.count = 0 # 具体的测试用例方法,一定要以test开头 # 测试方法必须有test字样开头 def testDouyu(self): self.driver.get("https://www.douyu.com/directory/all") # while True: soup = BeautifulSoup(self.driver.page_source, "lxml") # 房间名, 返回列表 names = soup.find_all("h3", {"class": "DyListCover-intro"}) print (names) # 观众人数, 返回列表 numbers = soup.find_all("span", {"class": "DyListCover-hot"}) print (numbers) # zip(names, numbers) 将name和number这两个列表合并为一个元组 : [(1, 2), (3, 4)...] for name, number in zip(names, numbers): print u"观众人数: -" + number.get_text().strip() + u"-\t房间名: " + name.get_text().strip() self.num += 1 # self.count += int(number.get_text().strip()) # 扩展:点击下一页 循环 # self.driver.find_element_by_class_name("dy-Pagination-item-custom").click() # 测试结束执行的方法 def tearDown(self): # 退出浏览器 self.driver.quit() if __name__ == "__main__": unittest.main()
效果:
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!