【发布时间】:2017-03-23 06:13:32
【问题描述】:
我正在使用 Python 和 Selenium 来抓取网页,在某些情况下,我无法让它工作, *
我想访问带有文本“PInt”的元素,这是下面代码中的第二个链接。 它的 xPath(从开发者控制台复制)是://[@id="submenu1"]/a[2]
<div id="divTest" onscroll="SetDivPosition();" style="height: 861px;">
<div class="menuTitle" id="title1">
<a href="#" onclick="toggle(1);"> </a>
</div>
<div class="subtitle" id="submenu1">
<img src="images/spacer.gif" border="0" width="2px" height="12px">
<a href="#" class="NormalBlueSmall" onclick="clickItem('area/search/mov/mov2','mov');">Mov</a><br>
<img src="images/spacer.gif" border="0" width="2px" height="12px">
<a href="#" class="NormalBlueSmall" onclick="clickItem('area/con/ExtInt/extInt','pIint');">PInt</a><br>
<img src="images/spacer.gif" border="0" width="2px" height="12px">
<a href="#" class="NormalBlueSmall" onclick="clickItem('GoToNew.asp?link=asw_cnt/SmanSwif.aspx','SMAN/SWIF');">SWAM / SWIF</a><br>
</div>
...
我的代码片段是:
try:
res = driver.find_elements_by_link_text('PInt')
print("res1:{}".format(res))
res = driver.find_element(By.XPATH,'//*[@id="submenu1"]/a[3]')
print("res:{} type[0]:{}".format(res,res[0]))
itm1 = res[0]
itm1.click()
我得到错误:
无法定位元素: {"method":"xpath","selector":"//*[@id="submenu1"]/a[2]"}
我的问题是,我怎样才能获得元素的正确 xPath 或任何其他方式来访问元素?
更新:
这可能很重要,问题在于
Message: invalid selector: Unable to locate an element with the xpath expression(我已经尝试了所有建议的解决方案)可能是在之前在网页(用户+密码)中进行身份验证之后,一切正常。
我注意到登录后的 url driver.current_url 是静态的(asp 页面)。
这也是我试图在框架集和 frame
html > frameset > frameset > frame:nth-child(1)
【问题讨论】:
-
元素是否在 iframe 中?您可能还需要等待它可用。
-
可以分享一下网址吗?
-
试试这个 xpath
//div[@id='submenu1']//a[2] -
@JeffC 它不在 iFrame 内,而是在
-
你需要切换到框架。您应该能够找到一些示例代码。试试看它是否有效。
标签: python selenium xpath web-scraping