Python 3.x 使用';美丽集团';和';向上向下';
我正在寻找一种使用python库Python 3.x 使用';美丽集团';和';向上向下';,python-3.x,beautifulsoup,Python 3.x,Beautifulsoup,我正在寻找一种使用python库BeautifulSoup和upsidedown安全地翻转HTML中所有文本的方法 from bs4 import BeautifulSoup import upsidedown soup = BeautifulSoup('''<p>Paragraph1</p> <p>Paragraph2</p>''' , 'html.parser') tags = soup.findAll('p') for tag in ta
BeautifulSoup
和upsidedown
安全地翻转HTML中所有文本的方法
from bs4 import BeautifulSoup
import upsidedown
soup = BeautifulSoup('''<p>Paragraph1</p> <p>Paragraph2</p>'''
, 'html.parser')
tags = soup.findAll('p')
for tag in tags:
for c in tag.contents:
c.string = upsidedown.transform(c.string)
print(soup)
从bs4导入美化组
从上往下导入
汤=美丽的汤(“”“第1段第2段”
,'html.parser')
tags=soup.findAll('p')
对于标记中的标记:
对于tag.contents中的c:
c、 string=upsidedown.transform(c.string)
印花(汤)
预期产出:
ᘔɥdɐɹƃɹɐԀ
实际产量:
第1段第2段
我还想要一些关于如何在更复杂的HTMLs中翻转文本的指导。
例如,如果我有嵌套的标记,我不想翻转标记本身,因为这会使HTML语法无效。您应该使用
replace\u with()
方法。
您只需更改以下行:
c.string = upsidedown.transform(c.string)
借
完整代码:
from bs4 import BeautifulSoup
import upsidedown
soup = BeautifulSoup('''<p>Paragraph1</p> <p>Paragraph2</p>'''
, 'html.parser')
tags = soup.findAll('p')
for tag in tags:
for c in tag.contents:
c.string.replace_with(upsidedown.transform(c.string))
print(soup)
<p>ІɥdɐɹƃɐɹɐԀ</p> <p>ᘔɥdɐɹƃɐɹɐԀ</p>
从bs4导入美化组
从上往下导入
汤=美丽的汤(“”“第1段第2段”
,'html.parser')
tags=soup.findAll('p')
对于标记中的标记:
对于tag.contents中的c:
c、 string.replace_为(upsidedown.transform(c.string))
印花(汤)
输出:
from bs4 import BeautifulSoup
import upsidedown
soup = BeautifulSoup('''<p>Paragraph1</p> <p>Paragraph2</p>'''
, 'html.parser')
tags = soup.findAll('p')
for tag in tags:
for c in tag.contents:
c.string.replace_with(upsidedown.transform(c.string))
print(soup)
<p>ІɥdɐɹƃɐɹɐԀ</p> <p>ᘔɥdɐɹƃɐɹɐԀ</p>
ᘔɥdɹƃɹɹԀ
谢谢,这回答了我的主要问题。