【问题标题】:FInd and Replace using Beautiful Soup使用 Beautiful Soup 查找和替换
【发布时间】:2018-07-13 00:11:33
【问题描述】:

尝试使用漂亮的汤和正则表达式替换。 Soup 找到了我需要的内容,然后将其转换为字符串并使用正则表达式进行替换,但它不起作用。有没有使用美汤的查找和替换。

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

【问题讨论】:

    标签: regex python-3.x beautifulsoup


    【解决方案1】:

    您想替换您找到的节点的文本内容。只需将.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>
    #                                  ^^^^^^^^
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2016-01-13
      • 2021-02-28
      相关资源
      最近更新 更多