下面是如何設定頁面的片段。
<class id="class1">
<ul>
<li>
<strong>section 1</strong>
<a href="link.com/home1">some link 1</a>
<li>
<strong>section 2</strong>
<a href="link.com/home">some link 2</a>
<class id="class1">
<ul>
<li>
<strong>section 3</strong>
<a href="link.com/home/abc">some link 3</a>
<li>
<strong>section 4</strong>
<a href="link.com/home/def">some link 4</a>
我如何在第 2 部分中找到 link.com/home?
我想這會奏效:
.class1:nth-of-type(1) li:nth-child(2) [href*="/home"]
但事實并非如此。它也可以在第 4 節中找到鏈接。我必須使用 *= 因為在不同的環境中 url 前綴會發生變化。
uj5u.com熱心網友回復:
為了完整起見,我在適當的地方添加了</li>,</ul>和</class>標簽,理想的 HTML 將是:
<class id="class1">
<ul>
<li>
<strong>section 1</strong>
<a href="link.com/home1">some link 1</a>
</li>
<li>
<strong>section 2</strong>
<a href="link.com/home">some link 2</a>
</li>
</ul>
</class>
<class id="class1">
<ul>
<li>
<strong>section 3</strong>
<a href="link.com/home/abc">some link 3</a>
</li>
<li>
<strong>section 4</strong>
<a href="link.com/home/def">some link 4</a>
</li>
</ul>
</class>
要定位第 2 部分的href屬性,您可以使用以下任一定位器策略:
使用
nth-child():class#class1 > ul li:nth-child(2) a[href$="home"]使用
nth-child():class#class1 > ul li:nth-of-type(2) a[href$="home"]
解決方案
要列印href屬性的值,您可以使用以下任一定位器策略:
使用
nth-child():print(driver.find_element(By.CSS_SELECTOR, "class#class1 > ul li:nth-child(2) a[href$='home']").get_attribute("href"))使用
nth-child():print(driver.find_element(By.CSS_SELECTOR, "class#class1 > ul li:nth-of-type(2) a[href$='home']").get_attribute("href"))
tl; 博士
p:nth-child(2) 和 p:nth-of-type(2) 有什么區別?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362066.html
