简体   繁体   English

Python Selenium(如果字符串包含完全匹配)

[英]Python Selenium if string contains exact match

I am trying to check a URL using python selenium to see what page the site is on. 我正在尝试使用python硒检查URL,以查看网站位于哪个页面上。 I have the following urls... 我有以下网址...

http://www.example.com
http://www.example.com/page1
http://www.example.com/contact

I am using this python... 我正在使用这个python ...

if "http://www.example.com" in url:
    print("The URL is homepage")
else:
    print("The URL is not homepage")

This isn't working because all of the URL contain the string, how can I change it so that it only works for an exact match? 由于所有URL都包含字符串,因此无法使用,如何更改它以便仅在完全匹配的情况下起作用?

Use the equality operator == as follows: 使用等于运算符== ,如下所示:

if url == "http://www.example.com":
    print("The URL is homepage")
else:
    print("The URL is not homepage")

It is convention to put the variable name on the LHS of the equality operator and the string you are testing it against on the RHS. 习惯上将变量名放在等式运算符的LHS上,并将要测试的字符串放在RHS上。

If you want to go a step further, you can use regular expressions 如果想进一步,可以使用正则表达式

import re

a = re.compile('.*example\.com$')
# .* ignores whatever comes before example.com
# \. escapes the dot
# $  indicates that this must be the end of the string

if a.match(url):  # <-- That's the URL you want to check
    print("The URL is homepage")
else:
    print("The URL is not homepage")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM