第一步就是安装Selenium这个模块,当然,前提是你的python已经安装好了
直接在dos窗口输入
pip install selenium完成一键安装
然后就可以新建一个py文件,在里面输入
from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0 # Create a new instance of the Firefox driver driver = webdriver.Firefox() # go to the google home page driver.get("http://www.google.com") # find the element that's name attribute is q (the google search box) inputElement = driver.find_element_by_name("q") # type in the search inputElement.send_keys("cheese!") # submit the form (although google automatically searches now without submitting) inputElement.submit() # the page is ajaxy so the title is originally this: print driver.title try: # we have to wait for the page to refresh, the last thing that seems to be updated is the title WebDriverWait(driver, 10).until(EC.title_contains("cheese!")) # You should see "cheese! - Google Search" print driver.title finally: driver.quit() |
这样就打开google进行查找cheese!后打印标题并关闭浏览器
下面介绍各种获取浏览器内的各种元素的方法
By ID <divid="coolestWidgetEvah">...</div> element=driver.find_element_by_id("coolestWidgetEvah") By Class Name <divclass="cheese"><span>Cheddar</span></div><divclass="cheese"><span>Gouda</span></div> cheeses=driver.find_elements_by_class_name("cheese") By Tag Name <iframesrc="..."></iframe> frame=driver.find_element_by_tag_name("iframe") By Name <inputname="cheese"type="text"/> cheese=driver.find_element_by_name("cheese") By Link Text <a href="http://www.google.com/search?q=cheese">cheese</a>> cheese=driver.find_element_by_link_text("cheese") By Partial Link Text <a href="http://www.google.com/search?q=cheese">search for cheese</a> cheese=driver.find_element_by_partial_link_text("cheese") By CSS <divid="food"><spanclass="dairy">milk</span><spanclass="dairy aged">cheese</span></div> cheese=driver.find_element_by_css_selector("#food span.dairy.aged") By XPATH <inputtype="text"name="example"/><INPUTtype="text"name="other"/> inputs=driver.find_elements_by_xpath("//input") |