Reputation: 1
I made a dictionary;
mydic = {
'ProductName1': 'mp1',
'ProductName2 : 'mp2',
'ProductName3' : 'mp3',
'ProductName4' : 'mp4'
}
url = "https://www.example.com"
result = requests.get(url)
soup = BeautifulSoup(result.text, "html.parser")
tagnames = soup.find_all("div", {"class": "one-line font-size-md"})
The output is list like this:
[< d i v c l a s s ="o n e - l i n e f o n t - s i z e - m d " > P r o d u c t N a m e 1 < / d i v > , < d i v c l a s s = " o n e - l i n e
f o n t - s i z e - m d " > P r o d u c t N a m e 2 < / d i v > , < d i v c l a s s = " o n e -l i n e f o n t - s i z e - m d " > P r o d u c t N a m e 3 < / d i v > , < d i v c l a s s = " o n e - l i n e f o n t - s i z e - m d " > P r o d u c t N a m e 4 < / d i v > ]
I want to replace ProductName1 with mydic
values mp1
, mp2
, mp3
, mp4
and save html file with replaced. I tried to change the format to string and replace but it couldn't be true.
Upvotes: 0
Views: 53
Reputation: 76
soup.find_all() will give you list of elements matching the selector .
you can try something like this
mydict = {
"ProductName1" : "mp1",
"ProductName2" : "mp2",
"ProductName3" : "mp3",
"ProductName4" : "mp4",
}
html = '''<div class ="one-line font-size-md">ProductName1</div> <div class ="one-line font-size-md"> ProductName2 </div> <div class ="one-line font-size-md"> ProductName3 </div> <div class ="one-line font-size-md"> ProductName4 </div>'''
sp = BeautifulSoup(html,"lxml")
divs = sp.find_all('div','one-line font-size-md')
for div in divs :
div.string = mydict[div.text.lstrip().rstrip()]
with open("output.html", "wb") as file:
file.write(sp.prettify("utf-8"))
Upvotes: 1