如何最好地选择正确的元素(python3,Selenium)

2024-09-29 21:45:29 发布

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

我试图使用python3和Selenium从页面中选择一个特定的元素。你知道吗

该页面由一个长列表(数百项)组成,其格式如下:

enter image description here

此表的html如下所示:

enter image description here

当我展开要单击的特定项目的元素时,它看起来是这样的(为了隐私而隐藏链接):

enter image description here

到目前为止,我一直在做的是搜索我需要使用的元素

titleField = 'Zombie Apocalypse'   
searchBuilder = "//*[contains(text(), '" + titleField + "')]"
searchForBook = browser.find_elements_by_xpath(searchBuilder)
searchForBook[0].click()

这在某些时候是有效的。当有两个项目的名称相同时,或者如果标题中有撇号,我就会遇到问题,有时我根本不明白为什么它不起作用。你知道吗

有没有比我使用的方法更好的方法从表中选择单个元素?我会提前知道物品的标题,但不会知道身份证号码。身份证号码就是我要搜集的信息。你知道吗

如果搜索返回项目的URL,我也可以接受,因为ID号包含在该URL中,所以我可以从那里提取它。但是标题不在URL中,所以我不知道如何搜索它。你知道吗


Tags: 项目方法url元素标题列表格式selenium
1条回答
网友
1楼 · 发布于 2024-09-29 21:45:29

在将文本插入XPath表达式之前,应该引用它。这将对xpath表达式的字符串进行适当编码。请注意,“quoteattr”ed sting包括周围的'"。你知道吗

from xml.sax.saxutils import quoteattr
titleField = quoteattr('Zombie Apocalypse')  # But may contain XML markup chars
searchBuilder = "//*[contains(text(), " + titleField + ")]"
searchForBook = browser.find_elements_by_xpath(searchBuilder)
searchForBook[0].click()

相关问题 更多 >

    热门问题