如何使用BeautifulSoup在一个单词上换行?

2024-05-14 10:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用beauthulsoup把单词列表转换成一个跨度。在

例如

<html><body>word-one word-two word-one</body></html>

必须是

^{pr2}$

其中word-one需要移动到范围中

到目前为止,我可以使用以下方法找到这些元素:

for html_element in soup(text=re.compile('word-one')):
    print(html_element)

然而,取代这样的文本来跨越还不清楚。在


Tags: 方法in元素列表forhtmlbodyelement
1条回答
网友
1楼 · 发布于 2024-05-14 10:16:33

我做过这样的事情,变量html是您的代码<html><body>word-one word-two word-one</body></html>,我将文本和代码分开,然后将它们添加到一起。在

soup = BeautifulSoup(html,'html.parser')
text = soup.text # Only the text from the soup

soup.body.clear() #Clear the text between the body tags

new_text = text.split() # Split beacuse of the spaces much easier

for i in new_text:
    new_tag = soup.new_tag('span') #Create a new tag
    new_tag.append(i) #Append i to it (from the list that's split between spaces)
    #example new_tag('a') when we append 'word' to it it will look like <a>word</a>
    soup.body.append(new_tag) #Append the whole tag e.g. <span>one-word</span)

我们也可以用正则表达式来匹配某个单词。在

^{pr2}$

我相信我们可以用类似的方式使用.insert。在

相关问题 更多 >

    热门问题