1

I develop a crawler with many actions. Many xpaths are involving and for this reason I use a json file for storing. Then crawler start running I would like to make a basic syntax check (before xpath usage) on xpaths and raise error for invalid xpaths.

for example:

xpath1 = '//*[@id="react-root"]/section'
xpath2 = '//*[[@id="react-root"]/section'
xpath3 = '//*[@id="react-root"]\section'

from these xpaths only xpath1 is valid

is there any module or regex which does this kind of validation?

2 Answers 2

7

You can compile the xpath strings with lxml.etree.XPath which will raise an exception if the syntax is incorrect:

>>> import lxml.etree
>>> lxml.etree.XPath('//*[@id="react-root"]/section')
//*[@id="react-root"]/section
>>> lxml.etree.XPath('//*[[@id="react-root"]/section')
Traceback (most recent call last):
  ...
lxml.etree.XPathSyntaxError: Invalid expression
>>> lxml.etree.XPath(r'//*[@id="react-root"]\section')
Traceback (most recent call last):
  ...
lxml.etree.XPathSyntaxError: Invalid expression
Sign up to request clarification or add additional context in comments.

1 Comment

that's exactly what I was looking for. Thank you!
-1
from selenium import webdriver;
webdriver.Chrome().find_elements('xpath', '//*[text(),"invalid xpath"]')

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.