Python selenium - 通过 xPath 获取元素并访问它

问题描述 投票:0回答:4

我正在使用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)

python selenium-webdriver web-scraping xpath
4个回答
3
投票

感谢@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 运行脚本,您需要设置一个显示:

30 5 * * * export DISPLAY=:0; python /usr/.../main.py

1
投票

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

使用xpath:

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

使用CSS选择器:

res = driver.find_element_by_css_selector('#submenu1 a:nth-of-type(2)')

1
投票

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

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

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


0
投票

在 chrome 中查找 xPath:

  1. 右键单击您想要的元素
  2. 检查,这将打开开发人员窗口并突出显示所选元素。
  3. 右键单击突出显示的元素并选择“复制”>“通过 xpath 复制”

这里列出了定位元素的所有不同方法定位元素

© www.soinside.com 2019 - 2024. All rights reserved.