Modifying the tree in beautifulsoup4?

I have a large html webpage, where I want to find all the links that have the "headline" class and change the webpage that they're pointing to (modify the href attribute in the anchor tag). The only tags with the headline class are those links.

for i in soup.find_all(attrs={"class":"headline"}):
    i["href"] = "NEW LINK I WANT THIS TO POINT TO"

This is how I'm trying to do it, but this is not actually modifying the tree in the soup object. It seems like the i["href"] is just a copy of the tag in the tree and that modifying it does not modify the tree? How can I fix this?

Thank you!

Edit:

Sorry! My bug was actually elsewhere in my code! This part works fine. Sorry for the hassle!

1 answer

  • answered 2018-07-11 05:05 ThatBird

    Is this what you're looking for?

    i["href"] = i["href"].replace(oldlink, newlink)