我正在学习Selenium,并且对XPath有相当的掌握。
我遇到的问题是,在一个网页上,有一个元素我想选择它,但它具有动态生成的id
和class
。我已经尝试了以下方法:
code = driver.find_element_by_xpath("//*[contains(@text='someUniqueString')]")
然而,该元素并没有任何文本。相反,它是一个带有 JSON 的 <code>
元素。
<codestyle="display: none" id="something-crazy-dynamic">
{"dataIWantToGrab":{"someUniqueString":...}}
</code>
我想用CPU搜索innerHTML
以查找唯一的字符串,但我找不到任何好的资源。
我已经尝试过:
driver.find_element_by_xpath("//*[contains(@innerHTML='someUniqueString')]")
但我收到了错误
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[contains(@innerHTML='someUniqueString')]
以下是我正在处理的兄弟文本的链接
https://gist.github.com/anonymous/b227e59c942e7ec9f5a851a3b7ecdfc6
我能够解决这个问题,但并非使用Selenium,而是使用Beautiful Soup。这不是一个理想的解决方案,但仍然是一个解决办法。
soup = BeautifulSoup(driver.page_source)
codes = soup.find_all("code")
found_json = [i for i in codes if i.text.find("someUniqueString") > 0]
id
的任何部分都是固定的还是全部都是动态的? - Guy