gawel / pyquery

A jquery-like library for python
http://pyquery.rtfd.org/
Other
2.3k stars 182 forks source link

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

Open bchopson opened 4 years ago

bchopson commented 4 years ago
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.

senpos commented 4 years ago

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 commented 4 years ago

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)