Calling and using an attribute stored in a variable (using Beautifulsoup 4)

I want to call Beautiful Soup attributes (e.g. class_, href, id) from a variable so that I can use it in functions like this:

script

from bs4 import BeautifulSoup data='<p class="story">xxx </p> <p id="2">yyy</p> <p class="story"> zzz</p>' def removeAttrib(data, **kwarg): soup = BeautifulSoup(data, "html.parser") for x in soup.findAll(tag, kwargs): del x[???] # should be an equivalent of: del x["class"] kwargs= {"class":"story"} removeAttrib(data,"p",**kwargs ) print(soup) 

Expected Result:

 <p>xxx </p> <p id="2">yyy</p> <p> zzz</p> 



MYGz solved the first problem using tag, argdict , using a dictionary as an argument to the function. Then I found **kwargs in this question (pass the key and value of the dictionary).

But I did not find a way for del x["class"] . How to pass a class key? I tried using ckey=kwargs.keys() and then del x[ckey] , but that didn't work.

ps1: any idea why removeAttrib (data, "p", {"class": "story"}) doesn't work? Ps2: This is another topic than this (this is not a duplicate)

+1
python beautifulsoup
Jan 22 '17 at 15:29
source share
2 answers

all credits MYGz and commandlineluser

 from bs4 import BeautifulSoup data='<p class="story">xxx </p> <p id="2">yyy</p> <p class="story"> zzz</p>' def removeAttrib(data, tag, kwargs): soup = BeautifulSoup(data, "html.parser") for x in soup.findAll(tag, kwargs): for key in kwargs: # print(key) #>>class x.attrs.pop(key, None) # attrs: to access the actual dict #del x[key] would work also but will throw a KeyError if no key print(soup) return soup data=removeAttrib(data,"p",{"class":"story"}) 
+1
Feb 09 '17 at 19:26
source share

Instead, you can pass a dictionary:

 from bs4 import BeautifulSoup data='<p class="story">xxx </p> <p id="2">yyy</p> <p class="story"> zzz</p>' soup = BeautifulSoup(data, "html.parser") def removeAttrib(soup, tag, argdict): for x in soup.findAll(tag, argdict): x.decompose() removeAttrib(soup, "p", {"class": "story"}) 
+1
Jan 22 '17 at 15:45
source share



All Articles