2

I am trying to scrape the restaurant names of a food delivery website, and the xpaths are randomly numerical. Not all the numbers exist, so when it tries a certain number for x, the error appears. This is some of my input:

    restaurantname = ['//li[{}]/a/div[2]/h4'.format(x) for x in range(1, 999)]
    for restaurant in restaurantname[:999]:
        title = driver.find_element_by_xpath(restaurant).text
        print(title)
        print('*'*5)

This is the output in my terminal after I run the python file:

Message: no such element: Unable to locate element: 
{"method":"xpath","selector":"//li[157]/a/div[2]/h4"}

How do I make it simply skip if there is "no such element?"

1
  • 3
    Try to catch the error with try except block. Commented Jan 29, 2019 at 23:48

1 Answer 1

4

You should surround your find_element_by_xpath() and print statements with a try/except block. This will allow you to handle the error with the keyword pass, which means "do nothing."

Good luck!

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! I played around with the try/except and it worked!
Hi @MimiChung if you find this answers your question you should except it!
@MosheSlavin what do you mean except it
@MimiChung great to hear!

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.