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

replace_with doesn't work for top level nodes #144

Open
djay opened this issue Aug 24, 2016 · 1 comment
Open

replace_with doesn't work for top level nodes #144

djay opened this issue Aug 24, 2016 · 1 comment

Comments

@djay
Copy link

djay commented Aug 24, 2016

for example

> print pq("<span/><div>foo</div>").filter("div").replace_with("<span>bah</span>")
<div><span/><div>foo</div></div>

The reason seems to be that replace_with expects a parent, which exists, but is not part of the original document.

Remove doesn't work either

pq("<span/><div>foo</div>",parser='html_fragments').filter("div").remove()
[<div>]
@djay
Copy link
Author

djay commented Aug 25, 2016

I think there are two things going on.

  1. remove and replace_with don't change whats in self.elements. So even though they remove it from some parent node somewhere, the pq object still includes the old set of nodes. That seems wrong.
  2. When using html_fragments parsing a new root node is created by not included in the pq object. The remove and replace_with will alter this parent. If you print out the children of this parent you will get the correct result.

For example this will get you the desired result

> doc = pq("<span/><div>foo</div>",parser='html_fragments')
> root = doc[0].getparent()
> print doc.filter("div").remove()
<div>foo</div>
> print (root.text or '') + ''.join([tostring(child) for child in root.iterchildren()])
<span/>

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

1 participant