【问题标题】:Inserting HTML into an html file using BeautifulSoup使用 BeautifulSoup 将 HTML 插入 html 文件
【发布时间】:2020-07-27 05:23:51
【问题描述】:

我有一个文件,其中包含指向不同页面的链接。我想用id="links" 将它们插入到div 下的HTML 文件中。需要明确的是,div 已经存在,所以我不想在任何地方创建新标签。

显示了我的 python 和 HTML 尝试

<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)

注意-我看过以下页面,但它们没有解决我的问题 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

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    soup.select() 将返回elements 的列表。要在单个元素内附加标签,您需要使用select_one()

    只需替换

    div = soup.select("#links")

    div = soup.select_one("#links")

    代码

    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)
    

    【讨论】:

    • 非常感谢。那行得通。您能否提供一个解释,以及为什么这样做有效,以及为什么不提供有问题的代码。这对未来的观众也会有所帮助。
    • @user185887 :谢谢队友刚刚添加它。
    猜你喜欢
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2019-01-27
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多