pyquery icon indicating copy to clipboard operation
pyquery copied to clipboard

Parsing an empty file causes exceptions when calling instance methods

Open bchopson opened this issue 5 years ago • 2 comments

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 avatar Mar 31 '20 17:03 bchopson

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.

senpos avatar May 02 '20 12:05 senpos

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)

gawel avatar May 02 '20 15:05 gawel