selenium+python find_element_by_css_selector方法使用


  • 1.通過類class獲取

      比如如下代碼

    <h1 class="important">
    This heading is very important.
    </h1>
    <p class="important">
    This paragraph is very important.
    </p>
    <p class="important warning">
    This paragraph is a very important warning.
    </p>

在上面的代碼中,兩個元素的 class 都指定為 important:第一個標題( h1 元素),第二個段落(p 元素)
1> 獲取class值為important的h1標簽

find_element_by_css_selector(h1.importane)
2>獲取所有class值為important的標簽

find_element_by_css_selector(*.importane)或者find_element_by_css_selector(.importane)
3>獲取class值為important warning的標簽

find_element_by_css_selector(.importane.warning)

 

 

  • 2.通過id獲取:

首先,ID 選擇器前面有一個 # 號 - 也稱為棋盤號或井號
<p id="intro">This is a paragraph of introduction.</p>

 find_element_by_css_selector(#"intro")

  • 3.屬性選擇器:

1>.

<a title="W3School Home" href="http://w3school.com.cn">W3School</a>

 屬性中包含了title和href,

find_element_by_css_selector('a[title][href]')

2>

<a href="http://www.w3school.com.cn/about_us.asp">About W3School</a>

 定位屬性中href="http://www.w3school.com.cn/about_us.asp"的元素,

find_element_by_css_selector('a[href="http://www.w3school.com.cn/about_us.asp"]')

3>

<a href="http://www.w3school.com.cn/" title="W3School">W3School</a>

 通過href和title來定位

find_element_by_css_selector("a[href='http://www.w3school.com.cn/about_us.asp'][title='W3School']")

4>部分屬性定位
<h1>可以應用樣式:</h1>
<img title="Figure 1" src="/i/figure-1.gif" />
<img title="Figure 2" src="/i/figure-2.gif" />

<hr />

<h1>無法應用樣式:</h1>
<img src="/i/figure-1.gif" />
<img src="/i/figure-2.gif" />

 定位title中包含有figure的元素:

find_element_by_css_selector("image[title~='figure']")


5>其他
[abc^="def"] 選擇 abc 屬性值以 "def" 開頭的所有元素
[abc$="def"] 選擇 abc 屬性值以 "def" 結尾的所有元素
[abc*="def"] 選擇 abc 屬性值中包含子串 "def" 的所有元素
  • 4.后代選擇器

<h1>This is a <em>important</em> heading</h1>
<p>This is a <em>important</em> paragraph.</p>

 find_element_by_css_selector("h1 em")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM