案例二:動态頁面模拟點選
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# python的測試子產品
import unittest
from selenium import webdriver
from bs4 import BeautifulSoup
class douyuSelenium(unittest.TestCase):
# 初始化方法
def setUp(self):
self.driver = webdriver.PhantomJS()
#具體的測試用例方法,一定要以test開頭
def testDouyu(self):
self.driver.get(\'http://www.douyu.com/directory/all\')
while True:
# 指定xml解析
soup = BeautifulSoup(driver.page_source, \'xml\')
# 傳回目前頁面所有房間标題清單 和 觀衆人數清單
titles = soup.find_all(\'h3\', {\'class\': \'ellipsis\'})
nums = soup.find_all(\'span\', {\'class\': \'dy-num fr\'})
# 使用zip()函數來可以把清單合并,并建立一個元組對的清單[(1,2), (3,4)]
for title, num in zip(nums, titles):
print u"觀衆人數:" + num.get_text().strip(), u"\t房間标題: " + title.get_text().strip()
# page_source.find()未找到内容則傳回-1
if driver.page_source.find(\'shark-pager-disable-next\') != -1:
break
# 模拟下一頁點選
self.driver.find_element_by_class_name(\'shark-pager-next\').click()
# 退出時的清理方法
def tearDown(self):
print \'加載完成...\'
self.driver.quit()
if __name__ == "__main__":
unittest.main()