一、selenium基本操作
from selenium import webdriver
from selenium.webdriver.common.keys import Keys #键类提供了模拟键盘输入
driver = webdriver.Chrome() #调用chrome
driver.get("https://www.baidu.com/") #访问网址
assert "baidu" in driver.title #断言,检查title是否含有baidu
elem = driver.find_element_by_name('wd')
#找到名字为wd的元素,此为搜索框。可以通过name.id.text,xpath查找
elem.clear() #清除搜索框里原本的东西
elem.send_keys("美女") #发送关键词
elem.send_keys(Keys.RETURN) #输入回车
elem.send_keys("与野兽", Keys.ARROW_DOWN) #按下箭头键接着输入
elem.send_keys(Keys.RETURN)
#driver.close() #关闭浏览器调用
#driver.find_element_by_id("submit").click() #点击名为提交的按钮
#driver.forward() 前进
#driver.back() 后退
#find_element_by_id 找元素的方法,要找多个则elements
#find_element_by_name
#find_element_by_xpath
#find_element_by_link_text
#find_element_by_partial_link_text
#find_element_by_tag_name
#find_element_by_class_name
#find_element_by_css_selector
# driver.page_souce #网页源代码
#site = driver.find_element_by_xpath('//*[@id="pins"]/li[1]/a/img')
#a = site.get_attribute('src') #获取属性
#b = site.text #获取文本
二、selenium测试
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()