Python - Find text using beautifulSoup then replace in original soup variable

前端 未结 1 1153
天涯浪人
天涯浪人 2020-12-15 07:30
commentary = soup.find(\'div\', {\'id\' : \'live-text-commentary-wrapper\'})
findtoure = commentary.find(text = re.compile(\'Gnegneri Toure Yaya\')).replace(\'Gnegne         


        
相关标签:
1条回答
  • 2020-12-15 07:48

    You cannot do what you want with just .replace(). From the BeautifulSoup documentation on NavigableString:

    You can’t edit a string in place, but you can replace one string with another, using replace_with().

    That's exactly what you need to do; take each match, then call .replace() on the contained text and replace the original with that:

    findtoure = commentary.find_all(text = re.compile('Gnegneri Toure Yaya'))
    for comment in findtoure:
        fixed_text = comment.replace('Gnegneri Toure Yaya', 'Yaya Toure')
        comment.replace_with(fixed_text)
    

    If you want to use these comments further, you'll need to do a new find:

    findtoure = commentary.find_all(text = re.compile('Yaya Toure'))
    

    or, if you all you need is the resulting strings (so Python str objects, not NavigableString objects still connected to the BeautifulSoup object), just collect the fixed_text objects:

    findtoure = commentary.find_all(text = re.compile('Gnegneri Toure Yaya'))
    fixed_comments = []
    for comment in findtoure:
        fixed_text = comment.replace('Gnegneri Toure Yaya', 'Yaya Toure')
        comment.replace_with(fixed_text)
        fixed_comments.append(fixed_text)
    
    0 讨论(0)
提交回复
热议问题