27

I use Regex to retrieve certain content from a search box on a webpage with selenium.webDriver.

searchbox = driver.find_element_by_class_name("searchbox")
searchbox_result = re.match(r"^.*(?=(\())", searchbox).group()

The code works as long as the search box returns results that match the Regex. But if the search box replies with the string "No results" I get error:

AttributeError: 'NoneType' object has no attribute 'group'

How can I make the script handle the "No results" situation?

3 Answers 3

30

I managed to figure out this solution: omit group() for the situation where the searchbox reply is "No results" and thus doesn't match the Regex.

try:
    searchbox_result = re.match("^.*(?=(\())", searchbox).group()
except AttributeError:
    searchbox_result = re.match("^.*(?=(\())", searchbox)
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any solution if I have multiple number of regexes and dont want to except them individually?
In your code ) is missing after searchbox or after group()
15

When you do

re.match("^.*(?=(\())", search_result.text)

then if no match was found, None will be returned:

Return None if the string does not match the pattern; note that this is different from a zero-length match.

You should check that you got a result before you apply group on it:

res = re.match("^.*(?=(\())", search_result.text)
if res:
    # ...

6 Comments

Thanks, can you give a more specific example of code? I basically want it to write "" to res if it finds nothing. Or alternatively, pass if using except.
@Winterflags You can check res is None, if it is, change it to "".
@Winterflags Also note that your regex is greedy, it matches "abc(def" in the following string abc(def(. Is that what you want?
I updated the question with if condition and traceback. It seems to refer back to the line with re.match even though I do if after regex.
The regex works as intended right now, perhaps overly greedy but it doesn't produce capture errors. If it's necessary to change it to account for None we can do that.
|
1

This error occurs due to your regular expression doesn't match your targeted value. Make sure whether you use the right form of a regular expression or use a try-catch block to prevent that error.

try:
    pattern = r"^.*(?=(\())"
    searchbox_result = re.match(pattern, searchbox).group()
except AttributeError:
    print("can't make a group")

Thank you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.