-*- coding;utf-8 -*-
from selenium import webdriver
dr = webdriver.Chrome()
dr.get("https://www.baidu.com")
#有八种元素定位方法:
#id, name, class name, tag name, link text,部分link text, xpath, css选择器 其中,find_elements_by_xxx 获取的是一组元素。
前7种:
<span id="s_kw_wrap" class="s_ipt_wr"><span class="soutu-btn"></span>
<span class="soutu-btn"></span>
<input type="text" class="s_ipt" name="wd" id="kw" maxlength="" autocomplete="off" value="">
<input></input>
</span>
<div id="u_sp" class="s-isindex-wrap s-sp-menu">
<a href="http://news.baidu.com" target="_blank" class="mnav">超长的新闻名称</a>
</div> #id
dr.find_element_by_id("kw")
#name
dr.find_element_by_name("wd")
#class name
dr.find_element_by_class_name("s_ipt")
#tag name (标签名称)
dr.find_element_by_tag_name("input") #适用于只有一个input标签
dr.find_elements_by_tag_name("input")[0].send_keys() #适用于多个input标签
dr.find_element_by_tag_name("//span/input[0]") #通过父级元素 #text link, 部分text link
dr.find_elements_by_link_text("超长的新闻名称")
dr.find_element_by_partial_link_text("新闻") #xpath
dr.find_element_by_xpath("//input[@id='kw']") # 双斜杠表示不确定
dr.find_element_by_xpath("/*[@id='kw']") # "*"表示所有元素
dr.find_element_by_xpath("//input[@name='wd']")
dr.find_element_by_xpath("//input[@class='s_ipt']")
dr.find_element_by_xpath("//input[@value='123']") dr.find_element_by_xpath("//span/input[0]")#通过父级
dr.find_element_by_xpath("//span[@class='bg s_ipt_wr']/input[0]")#通过父级 也可用多种属性集合
dr.find_element_by_xpath("//input[@id='kw' and @name='wd']")
CSS选择器:
<span id="s_kw_wrap" class="s_ipt_wr"><span class="soutu-btn"></span>
<span class="soutu-btn"></span>
<input type="text" class="s_ipt" name="wd" id="kw" maxlength="" autocomplete="off" value="">
</span> #class 用“.”
dr.find_element_by_css_selector(".s_ipt") #id 用“#”
dr.find_element_by_css_selector("#kw") #name
dr.find_element_by_css_selector("[name=wd]")
dr.find_element_by_css_selector("name='wd'")
dr.find_element_by_css_selector("//input[name='wd']") #组合
dr.find_element_by_css_selector("span>input.s_ipt") #通过父级
dr.find_element_by_css_selector("span>input#kw")
dr.find_element_by_css_selector("span.s_ipt_wr>input")