【问题标题】:I want to replace an html content with my own content我想用我自己的内容替换一个 html 内容
【发布时间】:2021-08-18 06:14:50
【问题描述】:

以下是 html 代码,我想将内容替换为“This is html code”。 代码运行没有错误,但没有任何改变,内容保持不变。

我想替换“全栈开发人员”。用“这是 html 代码”

soup='<meta content="A full stack developer." name="description"/>'

我的代码:

for i in soup.find_all("meta", "description"):

    var1=i.string
    var1.replace_with(var1.replace(var1, 'This is html code '))
    print(var1)
    
print(soup)

通过上述方法,我没有收到错误,但内容属性保持不变。

我也尝试了不同的方法,但我得到了这个错误:

'str' 对象没有属性 'replace_with'

谁能指导我如何用你自己的替换内容属性?

【问题讨论】:

    标签: python beautifulsoup replace attributes tags


    【解决方案1】:

    要访问标签属性,请使用[ ]:

    from bs4 import BeautifulSoup
    
    html_doc = '<meta content="A full stack developer." name="description" />'
    soup = BeautifulSoup(html_doc, "html.parser")
    
    # replace the attribute "content":
    soup.find("meta", {"name": "description"})["content"] = "This is html code"
    print(soup)
    

    打印:

    <meta content="This is html code" name="description"/>
    

    【讨论】:

    • 现在我得到这个错误:列表索引必须是整数或切片,而不是 str
    • 谢谢,我想通了,用soup.find代替soup.find_all。
    猜你喜欢
    • 2021-08-19
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    相关资源
    最近更新 更多