1
votes

I have a file which contains links to different pages. I want to insert them into my HTML file beneath a div with id="links". To be clear, the div already exists, so I don't want to create a new tag anywhere.

My python and HTML attempt are shown

<html>
<head>
</head>
<body>
	<div id="links">
	</div>
</body>
</html>
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('myhtml.html'),'html.parser')
div = soup.select("#links")
print(div)

content = '<a href="abcd.com">Link</a>'
div.append(BeautifulSoup(content,'html.parser'))

print(div)
print (soup)

Note- I have seen the following pages but they did not address my question Insert HTML into an element with BeautifulSoup Append markup string to a tag in BeautifulSoup Edit and create HTML file using Python Using BeautifulSoup to modify HTML Get contents by class names using Beautiful Soup

1

1 Answers

1
votes

soup.select() will return list of elements.To append tag inside a single element you need to use select_one()

Just replace

div = soup.select("#links")

to

div = soup.select_one("#links")

Code:

html='''<html>
<head>
</head>
<body>
    <div id="links">
    </div>
</body>
</html>'''

soup=BeautifulSoup(html,"html.parser")
div = soup.select_one("#links")
print(div)

content = '<a href="abcd.com">Link</a>'
div.append(BeautifulSoup(content,'html.parser'))

print(div)
print (soup)