【发布时间】:2021-08-19 01:37:28
【问题描述】:
我正在使用 lxml 和 beautifulsoup 库,实际上我的目标是从整个 html 代码中翻译特定标签的文本,我使用翻译库成功翻译它,但我想要的是,我想替换带有翻译文本的特定标签的文本。
这里是html代码:
<p class="text_obisnuit2">What is a performer?</p>
<p class="text_obisnuit2">Leadership: Performer</p>
<p class="text_obisnuit2">Question:</p>
所以上面的 html 有英文文本。我想要的输出类型应该是罗马尼亚语:
<p class = "text_obisnuit2"> Ce este un interpret? </p>
<p class = "text_obisnuit2"> Conducere: interpret </p>
<p class = "text_obisnuit2"> Întrebare: </p>
我想你们已经明白了。
所以我想为特定的 xpath 设置一个循环,所有翻译的文本都应该一个接一个地插入其中。
这是我的代码:
from bs4 import BeautifulSoup, NavigableString, Tag
import requests
import time
import pandas as pd
import translators as ts
import json
import numpy as np
import regex
import selenium
from lxml import html
import time
import lxml.html
#r=requests.get(input('Enter the URL of your HTML page:\n'))
r=requests.get('https://neculaifantanaru.com/en/definition-what-is-a-performer.html')
soup=BeautifulSoup(r.text, 'html.parser')
page=r.content
element = html.fromstring(page)
for item in element.xpath('//div[@align = "justify"]/p[@class = "text_obisnuit2"]'):
text=item.text.content()
output=ts.google(text, from_language='en', to_language='ro')
for z in soup.find_all('p', attrs={'class':'text_obisnuit2'}):
var1=z.string
var1.replace_with(var1.replace(var1, output))
print(soup)
我得到的输出:
<p class="text_obisnuit2">Ce este un interpret? </p>
<p class="text_obisnuit2">Ce este un interpret? </p>
<p class="text_obisnuit2">Ce este un interpret? </p>
AttributeError: 'NoneType' object has no attribute 'replace_with'
我想要的输出:
<p class = "text_obisnuit2"> Ce este un interpret? </p>
<p class = "text_obisnuit2"> Conducere: interpret </p>
<p class = "text_obisnuit2"> Întrebare: </p>
注意:
应该有一个循环在所有这些标签中插入翻译后的文本,我的意思是所有标签都应该在使用循环翻译后得到自己的文本。
我无法解释更多,请任何人指导我。
【问题讨论】:
标签: python xpath beautifulsoup python-requests lxml