Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parsing an empty file causes exceptions when calling instance methods #209

Open
bchopson opened this issue Mar 31, 2020 · 2 comments
Open

Comments

@bchopson
Copy link

with open('file.txt', 'w') as f:
    f.write('')
pq = PyQuery(filename='file.txt')
pq.find('div')

raises an attribute error. It doesn't appear PyQuery can do anything useful with an empty file, so perhaps it would be better to raise an exception when calling the PyQuery constructor on an empty file? Calling PyQuery on an empty string (rather than empty file) raises an lxml error.

@bchopson bchopson changed the title Parsing an empty file causes exceptions in instance methods Parsing an empty file causes exceptions when calling instance methods Mar 31, 2020
@senpos
Copy link

senpos commented May 2, 2020

https://github.com/gawel/pyquery/blob/master/pyquery/pyquery.py#L56

try:
   result = getattr(etree, meth)(context)
except etree.XMLSyntaxError as e:
   if e.msg.startswith('Document is empty'):
       raise

@gawel
Do you think it is a valid way to solve it?

At first, I tried to check e.code == 4, since 4 is XML_ERR_DOCUMENT_EMPTY, but it turned out, that this error code appears not only when document is empty. So, I ended up with checking exception message.

@gawel
Copy link
Owner

gawel commented May 2, 2020

I guess it's ok if you check e.code == 4 and e.msg.startswith('Document is empty')

Just make sure the message is never translated (i18n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants