<p>首先,我建议您使用googletranslateapi,而不是刮Google页面。API是一个百倍容易,无麻烦,合法和传统的方式来做这件事。你知道吗</p>
<p>但是,如果您想解决这个问题,这里有一个解决方案。
你不是在处理机器人检测。谷歌的机器人检测功能非常强大,它只会打开Google <code>re-captcha</code>页面,甚至不会显示你想要的网页。
这里的问题是,翻译结果不会使用您使用的URL返回。这个URL只显示基本的翻译页面,结果稍后由<code>javascript</code>获取,并在页面加载后显示在页面上。javascript不被<code>python-requests</code>处理,这就是为什么类甚至不存在于您正在访问的<code>web-page</code>中的原因。你知道吗</p>
<p>解决方案是跟踪数据包并检测<code>URL</code>正在使用哪个<code>javascript</code>来获取结果。幸运的是,我找到了用于此目的的<code>URL</code>。
如果您请求<code>https://translate.google.com/translate_a/single?client=webapp&sl=en&tl=fr&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=gt&source=bh&ssel=0&tsel=0&kc=1&tk=327718.241137&q=goodmorning</code>,您将得到翻译程序的响应,即JSON。您可以解析JSON以获得所需的结果。
在这里,您可以面对Bot检测,它可以直接抛出http403错误。你知道吗</p>
<p>您还可以使用<code>selenium</code>来处理<code>javascript</code>并给出结果。代码中的以下更改可以使用<code>selenium</code>修复它</p>
<pre><code>from selenium import webdriver
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
#https://translate.google.com/#view=home&op=translate&sl=en&tl=en&text=hello
#tlid-transliteration-content transliteration-content full
class Phonetizer:
def __init__(self,sentence : str,language_ : str = 'en'):
self.words=sentence.split()
self.language=language_
def get_phoname(self):
for word in self.words:
print(word)
url="https://translate.google.com/#view=home&op=translate&sl="+self.language+"&tl="+self.language+"&text="+word
print(url)
#req = Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'})
#webpage = urlopen(req).read()
driver = webdriver.Chrome()
driver.get(url)
webpage = driver.page_source
driver.close()
f= open("debug.html","w+")
f.write(webpage.decode("utf-8"))
f.close()
#print(webpage)
bsoup = BeautifulSoup(webpage,'html.parser')
phonems = bsoup.findAll("div", {"class": "tlid-transliteration-content transliteration-content full"})
print(phonems)
#break
</code></pre>