gawel / pyquery

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

replace_with give an attributeerror traceback #105

Open zhaoguixu opened 9 years ago

zhaoguixu commented 9 years ago
from pyquery.pyquery import PyQuery as pq
doc = pq("<html><div /></html>")
node = pq("<span />")
doc.replace_with(node)

Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/pyquery/pyquery.py", line 1324, in replace_with self.class(tag).before(value + (tag.tail or '')) File "/usr/local/lib/python2.7/dist-packages/pyquery/pyquery.py", line 1199, in before if not parent.text: AttributeError: 'NoneType' object has no attribute 'text'

Why give an attributeerror traceback?

gawel commented 9 years ago

node must be a lxml element. doc.replace_with(node[0]) should work

zhaoguixu commented 9 years ago

It still does not work. Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/pyquery/pyquery.py", line 1324, in replace_with self.class(tag).before(value + (tag.tail or '')) TypeError: unsupported operand type(s) for +: 'lxml.etree._Element' and 'str'

It seems that you forget to check whether the parent of a tag is None?

gawel commented 9 years ago

Looks like I was wrong: must be text

https://github.com/gawel/pyquery/blob/master/tests/test_pyquery.py#L448

zhaoguixu commented 9 years ago

the docstring of the replace_with specifies it can be a PyQuery instance.

 def replace_with(self, value):
       """replace nodes by value::
            >>> doc = PyQuery("<html><div /></html>")
            >>> node = PyQuery("<span />")
            >>> child = doc.find('div')
            >>> child.replace_with(node)
            [<div>]
            >>> print(doc)
            <html><span/></html>
        """

I think the root cause is you fail to check the parent of the tag.

zhaoguixu commented 9 years ago

The parent should be checked, do you think so? It still gives the traceback. doc.replace_with('') Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/pyquery/pyquery.py", line 1324, in replace_with self.class(tag).before(value + (tag.tail or '')) File "/usr/local/lib/python2.7/dist-packages/pyquery/pyquery.py", line 1199, in before if not parent.text: AttributeError: 'NoneType' object has no attribute 'text'

gawel commented 9 years ago

Looks like you're deep in the code. Feel free to provide a fix. It will be merged except if it break tests. Even better if you provide new test(s)

zhaoguixu commented 9 years ago

I just simply check the code. Some other places also ignore the check. I will try. Thanks!