Python selenium获取元素的xPath并访问i

2024-05-22 00:41:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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>


...

我的代码是:

^{pr2}$

我得到了一个错误:

Unable to locate element: {"method":"xpath","selector":"//*[@id="submenu1"]/a[2]"}

我的问题是,如何获得元素的正确xPath或任何其他访问元素的方法?在

更新: 这可能很重要 Message: invalid selector: Unable to locate an element with the xpath expression(而且我已经尝试过所有建议的解决方案)可能是这是在认证后在网页(User+Pwd)之前,一切正常。 我注意到登录后的url driver.current_url是静态的(asp页面)。 另外,我尝试在一个框架集和框架中访问这一部分

html > frameset > frameset > frame:nth-child(1)


Tags: divsrcid元素imgwidthgifclass
3条回答

要查看使用selenium选择元素的所有方法的完整列表,可以在documentation中阅读有关它的所有信息。在

使用xpath:

res = driver.find_element_by_xpath(u'//*[@id="submenu1"]/a[2]')

使用css选择器:

^{pr2}$

尝试使用下面的任何xpath。有时自动生成的xpath不起作用。在

//a[contains(text(),'PInt')]
or
//div[@id='submenu1']//a[contains(text(),'PInt')]

另外,我建议您在单击上面的链接之前设置一些等待时间,以防上面的xpath不起作用

感谢@JeffC给我指出了正确的方向。在

由于页面有一些框架,我通过切换到正确的框架(使用xPath)来首先访问元素 然后访问元素。在

driver.switch_to.default_content()
driver.switch_to.frame(driver.find_element_by_xpath('html / frameset / frameset / frame[1]'))

driver.find_element_by_xpath("//a[contains(text(),'PInt')]").click()

顺便说一句,如果您想从crontab运行脚本,您需要设置一个显示:

^{pr2}$

相关问题 更多 >