在python中按链接文本(忽略字符串中的符号)查找元素

2024-04-26 22:34:09 发布

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

我试着把网上的字符串和我传递的字符串匹配起来。 web上的字符串包含像-,:;这样的符号,我传递的字符串没有符号

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
name="Ant Man and the Wasp"
driver=webdriver.Firefox()
driver.get("https://www.movieshunters.com")
search=driver.find_element_by_id('s')
search.clear()
search.send_keys(name)
driver.find_element_by_class_name('search-button').submit()
driver.find_element_by_link_text(name.title()).click()
<a href="https://www.movieshunters.com/movies/ant-man-and-the-wasp/">Ant-Man and the Wasp</a>

Tags: andthe字符串namefromimportsearchby
1条回答
网友
1楼 · 发布于 2024-04-26 22:34:09

您可以使用xpath实现这一点。翻译是您必须使用的方法。你知道吗

driver.find_element_by_xpath("//a[translate(.,'-',' ') = 'Ant Man and the Wasp']").get_attribute('href')

在你的代码里

driver.find_element_by_xpath("//a[translate(.,'-',' ') = name]").get_attribute('href')

阅读有关translate方法的更多信息。你知道吗

如果您想以任何顺序处理:-;,那么使用下面的xpath。你知道吗

//a[translate(.,'-;:','   ')='Ant Man and the Wasp']

屏幕截图:enter image description here

相关问题 更多 >