【问题标题】:How to extract the <span> tag contents using the Beautiful Soup?如何使用 Beautiful Soup 提取 <span> 标签内容?
【发布时间】:2017-12-31 12:22:22
【问题描述】:

我正在尝试从谷歌翻译网站中提取 span 标签内容。内容是具有 id="result_box" 的翻译结果。 当尝试打印内容时,它返回 None 值。

请查看图片here

import requests
from bs4 import BeautifulSoup

r = requests.get("https://translate.google.co.in/?rlz=1C1CHZL_enIN729IN729&um=1&ie=UTF-8&hl=en&client=tw-ob#en/fr/good%20morning")

soup = BeautifulSoup(r.content, "lxml")
spanner = soup.find(id = "result_box")

result = spanner.text

【问题讨论】:

  • 问题是请求不执行javascript,所以如果你访问你试图废弃的链接,你会看到类似imgur.com/a/lwSc5的东西。这就是为什么总是返回 None。
  • @AnkitDev 结果可能是由javascript设置的,因此当你发送请求时它不存在于正文中。模拟浏览器你可以使用seleniumselenium-python.readthedocs.io
  • 如果你需要谷歌翻译你应该检查这个ctrlq.org/code/19909-google-translate-api
  • 在您投入大量精力之前,请记住,如果您执行大量自动请求,Google 会阻止您。 (虽然您在使用验证码图像验证您不是机器人后仍然可以使用它)。

标签: python python-3.x web-scraping beautifulsoup python-requests


【解决方案1】:

请求不执行 JavaScript,您可以使用 seleniumPhantomJS 进行无头浏览,如下所示:

from bs4 import BeautifulSoup
from selenium import webdriver

url = "https://translate.google.co.in/?rlz=1C1CHZL_enIN729IN729&um=1&ie=UTF-8&hl=en&client=tw-ob#en/fr/good%20morning"
browser = webdriver.PhantomJS()
browser.get(url)
html = browser.page_source

soup = BeautifulSoup(html, 'lxml')
spanner = soup.find(id = "result_box")
result = spanner.text

这给出了我们预期的结果:

>>> result
'Bonjour'

【讨论】:

  • 谢谢 Vinícius,这是一个好主意,它实际上解决了许多其他问题。然而,上面的代码需要大约 5-6 秒的时间来执行并给出输出,它会在屏幕上留下一个 phantomjs.exe 窗口。有什么办法可以加快执行时间并摆脱那个exe窗口?
  • 很高兴为您提供帮助!我不确定性能,也许 ChromeDriver 更快,但我真的没有这方面的知识。关于隐藏命令行,我没试过,不过这个问题好像是你想要的:stackoverflow.com/questions/25871898/…
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 2021-02-22
  • 1970-01-01
  • 2020-08-24
  • 2021-01-24
  • 2020-05-04
  • 1970-01-01
  • 2018-01-15
相关资源
最近更新 更多