Skip to content

Add exception on failed query for early validation and better debug #143

@vgavro

Description

@vgavro

Consider this boilerplate code:

divs = selector.css('div.notexisted')
if not len(divs):
    raise ParseError(
        'Query %s failed on %s'
        % ('div.notexisted', shorten(selector.get(), 40))
    )

We may add following methods to raise ParseError (or FindError?) and do not break backward compatibility:

selector.xpath_or_error  # raises if query didn't match anything
selector.xpath_first  # returns first, raises if query didn't match anything
selector.xpath_one  # returns first, raises if query didn't match or return more than first element.
selector.css_*  # same

or add parameter to xpath and css methods:

match=False  # default, do not break backward compatibility
match=True  # raise ParseError if selector didn't return anything
match=int  # raise ParseError if returned elements length didn't matched

I prefer ParseError name (because of "Parsel") and second option as it's easier to implement.
For first option you may see as example https://github.com/vgavro/requests-client/blob/master/requests_client/lxml.py

Please give me feedback so I may work on pull request, or how do you solve problem with early validation? Thank you.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions