安装好selenium后,还需要下载浏览器对应的driver
下载chrome对应版本的chromedriver,设置chrome的环境变量。
没装chromedirver前,报错如下
(selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home)
from selenium import webdriver from time import sleep driver = webdriver.Chrome() #首字母大写 driver.get('http://www.cnblogs.com/liwenzhou/p/7988087.html') #:Usage:element = driver.find_element(By.ID, 'foo') text1 = driver.find_element_by_xpath("//table[4]/tbody/tr[2]") print(text1)
print(text1.text) text1 = driver.find_element_by_xpath("//table[4]/tbody") # print(type(text1.text)) #<class 'str'> t = text1.text
t = t.split(" ") # 一行一个元素 print(list(t)) # 定位第二行第二个元素 t = list(t) t = t[1].split(" ") #['password', '密码输入框', '<input', 'type="password"', '', '/>'] print(t[1]) # '密码输入框' driver.quit()
基于Python查找元素的其他方法:
driver.find_element_by_tag_name("tr")
driver.find_element_by_xpath("/div")
driver.find_element_by_id("101")
driver.find_element_by_css_selector("cssselector")
driver.find_element_by_class_name("classname")
driver.find_element_by_link_text("link")
driver.find_element_by_name("username")
多个元素是,也可以对元素进行随机操作