[英]What is the best way to search case insensitive text using Selenium in Python?
The first column of row are email addresses.行的第一列是电子邮件地址。 I send that value to a search bar and click search and then I wait until the search results come through.
我将该值发送到搜索栏并单击搜索,然后等待搜索结果通过。 Then I have this following if statement to search if that email address popped up in the results.
然后我有以下 if 语句来搜索结果中是否弹出该电子邮件地址。
But for the life of me, I can't figure out how to make the search case insensitive.但是对于我的生活,我无法弄清楚如何使搜索不区分大小写。 So that if I send 'test@email.com' and it finds 'tEsT@EMAIL.com' it will return true.
因此,如果我发送“test@email.com”并找到“tEsT@EMAIL.com”,它将返回true。
if driver.find_elements_by_xpath("(//*[contains(text(), '" + row[1] + "')] | //*[@value='" + row[1] + "'])"):
foundEmails += 1
print("Found Email: " + row[1])
Set the text to lowercase first so that it can be matched:首先将文本设置为小写,以便匹配:
if driver.find_elements_by_xpath("(//*[contains(text(), '" + row[1] + "')] | //*
[@value='" + row[1] + "'])"):
row[1] = row[1].lower() #assuming that this is the outputname, as you print this
foundEmails += 1
print("Found Email: " + row[1])
Okay, I found the solution to my problem, for some reason upper-case and lower-case don't work, so I have to use translate()好的,我找到了我的问题的解决方案,由于某种原因大写和小写不起作用,所以我必须使用 translate()
if driver.find_elements_by_xpath('//*[contains(translate(text(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", '
'"abcdefghijklmnopqrstuvwxyz"), "{0}")]'.format(row[1].lower())):
matches() is an XPATH 2.0 function that allows for case-insensitive regex matching. match()是一个 XPATH 2.0 函数,它允许不区分大小写的正则表达式匹配。
One of the flags is i
for case-insensitive matching.标志之一是
i
用于不区分大小写的匹配。
You can use following XPATH
with the matches()
function with the case-insensitive flag:您可以将以下
XPATH
与带有不区分大小写标志的matches()
函数一起使用:
if driver.find_elements_by_xpath("(//*[matches(text(), '" + row[1] + "','i')] | //*[matches(@value,'" + row[1] + "','i')])"):
foundEmails += 1
print("Found Email: " + row[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.