【发布时间】:2020-04-20 06:06:18
【问题描述】:
我正在使用 Python Selenium 通过 nth-child(n) 来定位元素。
下面是我的html代码:
<div id="iopop" style="">
<div style="" class="">
<div id="iopoph" class="animated zoomIn" style=" ">
<span style="" class="gs_hover"></span>
<b class="in">FALAFEL</b>
<a iid="128-73" class="itemsub lowend" price="2.99" name="FALAFEL (6)" style="">
<b class="in">(6)</b>
<b class="is"></b>
<b class="ip">2.99</b>
<b class="iq"></b></a>
<a iid="128-74" class="itemsub lowend" price="4.99" name="FALAFEL (12)" style="">
<b class="in">(12)</b>
<b class="is"></b>
<b class="ip">4.99</b>
<b class="iq"></b>
</a>
<b class="is"></b>
<b class="ip"></b>
<b class="iq"></b>
</div>
</div>
</div>
现在我想通过使用 nth-child(n) 来定位第一个 a 标签,所以我尝试了:
driver.find_element_by_css_selector('div#iopoph a:nth-child(2)').click()
但是有一个错误说:
NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"div#iopoph a:nth-child(2)"}
(Session info: chrome=79.0.3945.88)
有朋友可以帮忙吗?
【问题讨论】:
-
要定位第一个
<a>标签,您可以使用:nth-of-type代替:'div#iopoph a:nth-of-type(1)' -
第一个a是第三个孩子,所以a:nth-child(3)
标签: python selenium selenium-webdriver css-selectors webdriver