1. 安装
pip install selenium
2. 打开一个页面
driver = webdriver.PhantomJS(executable_path='/home/tian/下载/phantomjs-2.1.1-linux-x86_64/bin/phantomjs')
driver.get('https://www.baidu.com')
3.与页面交互
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
4. 查找元素
(https://selenium-python-zh.readthedocs.io/en/latest/locating-elements.html#locating-elements "Permalink to this headline")
在一个页面中有很多不同的策略可以定位一个元素。在你的项目中, 你可以选择最合适的方法去查找元素。Selenium提供了下列的方法给你:
- find_element_by_id
- 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
一次查找多个元素 (这些方法会返回一个list列表):
- find_elements_by_name
- find_elements_by_xpath
- find_elements_by_link_text
- find_elements_by_partial_link_text
- find_elements_by_tag_name
- find_elements_by_class_name
- find_elements_by_css_selector
4.1. 通过ID查找元素
login_form = driver.find_element_by_id('loginForm')
4.2. 通过Name查找元素
username = driver.find_element_by_name('username')
password = driver.find_element_by_name('password')
4.3. 通过XPath查找元素
login_form = driver.find_element_by_xpath("/html/body/form[1]")
login_form = driver.find_element_by_xpath("//form[1]")
login_form = driver.find_element_by_xpath("//form[@id='loginForm']")
网友评论