【问题标题】:How can I change a text in BeautifulSoup and keep the HTML code not effected如何更改 BeautifulSoup 中的文本并保持 HTML 代码不受影响
【发布时间】:2021-12-18 02:00:28
【问题描述】:

我正在尝试提取特定的 HTML 标记并翻译其中的文本值并用翻译后的值替换文本。我正在使用python和bs4。我一直在考虑字符串替换,但我不知道如何将 BeautifulSoup 作为字符串处理。 这是我提取的html代码

<p style="text-align: center;">Everyone Active has opened its own online shop that’s packed with fantastic quality fitness equipment that’s perfect for helping you work out at home at incredible prices. Follow the link below to find out more.</p>

我希望最终结果是:

<p style="text-align: center;">Everyone Active ha abierto su propia tienda en línea que está repleta de equipos de fitness de calidad fantástica que son perfectos para ayudarte a hacer ejercicio en casa a precios increíbles. Sigue el enlace de abajo para descubrir mas.</p>

【问题讨论】:

    标签: python web-scraping beautifulsoup python-requests web-crawler


    【解决方案1】:

    使用replace_with()

    你可以这样做。

    from bs4 import BeautifulSoup
    
    s= """
    <p style="text-align: center;">Everyone Active has opened its own online shop that’s packed with fantastic quality fitness equipment that’s perfect for helping you work out at home at incredible prices. Follow the link below to find out more.</p>
    """
    soup = BeautifulSoup(s, 'lxml')
    p_tag = soup.find('p')
    
    #Replacing the Text
    p_tag.string.replace_with('Everyone Active ha abierto su propia tienda en línea que está repleta de equipos de fitness de calidad fantástica que son perfectos para ayudarte a hacer ejercicio en casa a precios increíbles. Sigue el enlace de abajo para descubrir mas.')
    
    print(soup)
    

    输出:

    <html>
     <body>
      <p style="text-align: center;">
       Everyone Active ha abierto su propia tienda en línea que está repleta de equipos de fitness de calidad fantástica que son perfectos para ayudarte a hacer ejercicio en casa a precios increíbles. Sigue el enlace de abajo para descubrir mas.
      </p>
     </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      相关资源
      最近更新 更多