代码之家  ›  专栏  ›  技术社区  ›  user3525290

用靓汤找替代

  •  1
  • user3525290  · 技术社区  · 8 年前

    尝试用漂亮的汤和regex来代替。soup找到了我需要的东西,然后将其转换为字符串并使用regex替换,但它不起作用。有没有用靓汤找替代品。

    soup = BeautifulSoup(file_data, 'html.parser')
    found_data = soup.find(class_='front_page_feature')
    
    found_data = str(found_data)
    print(re.sub(found_data, mysql_data,file_data,flags = re.DOTALL))
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Wiktor Stribiżew    8 年前

    要替换找到的节点的文本内容。只要把 .string 具有 mysql_data 要更改它:

    >>> from bs4 import BeautifulSoup
    >>> file_data = """<p class="front_page_feature">Some data</p><p class="else">Other data</p>"""
    >>> soup = BeautifulSoup(file_data, 'html.parser')
    >>> found_data = soup.find(class_='front_page_feature')
    >>> mysql_data = "New Text"
    >>> found_data.string = mysql_data
    >>> soup
    # => <p class="front_page_feature">New Text</p><p class="else">Other data</p>
    #                                  ^^^^^^^^
    

    您当然可以用任何其他方式操作文本,甚至可以使用regex。