0

我是一名 python 开发人员,仍在学习,我需要一些关于抓取概念的帮助,我只想告诉你我想要什么。下面是html代码。包含不同的标签,如“em”、p 和 span。

类是不同的,分别命名为 obisnuit 和 obisnuit2。

html1="""<p class="text_obisnuit2">Best 3 developers.</p>
        <p class="text_obisnuit">There are best three types of web developers in world.</p>
        <p class="text_obisnuit2"><em>A javascript web developer.</em></p>
        <p class="text_obisnuit"><em>A nodeJS web developer.</em></p>
        <p class="text_obisnuit"><em>A python web developer <span class="text_obisnuit2">Django developer</span></em></p>
"""

我正在尝试在它们之间翻译文本并插入文本的翻译版本,我在这件事上取得了成功,但问题出在标签中。

下面是我的代码: 当我尝试使用此方法抓取文本时,删除了 em 标签,并且仅成功插入了文本。

from bs4 import BeautifulSoup
import translators as ts
soup1=BeautifulSoup(html1, 'html.parser')

articles = soup1.find_all('p', {'class':"text_obisnuit"})
for a in articles:  

    original_text=a.text
    #print(original_text)
    translated_output=ts.google(original_text, from_language='en', to_language='ro')


    a.string = translated_output.lower()
    print(a.string)



        

运行上述方法后,输出为:

OUTPUT>>

<p class =" text_obisnuit2 "> Cei mai buni 3 dezvoltatori. </p>
<p class = "text_obisnuit"> Există cele mai bune trei tipuri de dezvoltatori web din lume. </p>
<p class = "text_obisnuit2"> Un dezvoltator web javascript. </p>
<p class = "text_obisnuit"> Un dezvoltator web nodeJS. </p>
<p class = "text_obisnuit"> Un dezvoltator web Python <span class = "text_obisnuit2"> Dezvoltator Django </span> </p>

如果你看清楚了,em标签是从输出中去掉的,所以我不希望它被去掉,我希望翻译后的html结构相同。

我也尝试过这种方法,但只抓取了 em 标签的文本,而不是整个 html 文本。

articles = soup1.find_all('em')
for item in articles:    
    original_text=item.text.strip()
    #print(original_text)
    translated_output=ts.google(original_text, from_language='en', to_language='ro')
    #print(item)

    item.string=translated_output
    
    

我想要的输出应该是:

OUTPUT>>

<p class =" text_obisnuit2 "> Cei mai buni 3 dezvoltatori. </p>
<p class = "text_obisnuit"> Există cele mai bune trei tipuri de dezvoltatori web din lume. </p>
<p class = "text_obisnuit2"><em> Un dezvoltator web javascript. </em></p>
<p class = "text_obisnuit"><em> Un dezvoltator web nodeJS. </em></p>
<p class = "text_obisnuit"><em> Un dezvoltator web Python <span class = "text_obisnuit2"> Dezvoltator Django </span></em> </p>

请任何人指导我。

4

1 回答 1

0

问题在于,在您的 html 中,文本元素有时是其直接子元素<p>,有时埋在下面两三层。在你的原始 html 上试试这个,看看它是否有效:

for item in articles:
    targets = item.find_all()
    if len(targets)==0:        
        item.string=ts.google(item.string, from_language='en', to_language='ro')
    else:
      #EDIT: the next line was dropped: 
      for target in targets:
        if target.string:
            target.string=ts.google(target.string, from_language='en', to_language='ro')
于 2021-06-03T16:24:24.517 回答