【问题标题】:Scraping no display hidden visibility python刮不显示隐藏可见性python
【发布时间】:2018-06-03 16:17:48
【问题描述】:

我正在尝试在 python 中使用 Beautifulsoup 从网站上抓取数据,当我解析页面时,我想要抓取的信息没有显示出来,而是我看到了这个:

<span class="frwp-debug hidden" style="display: none!important; visibility: hidden!important;">  

解析后的 html 与我检查页面时看到的不同。

这是我的代码:

site = "http://www.fifa.com/worldcup/stories/y=2017/m=11/news=australia-2921204.html#World_Cup_History" 
hdr = {'User-Agent': 'Mozilla/5.0'} 
page = requests.get(site) 
soup = BeautifulSoup(page.text, "html.parser") 
print(soup.prettify())

如何抓取隐藏信息?

【问题讨论】:

  • BeautifulSoup 正确解析 HTML - 只是页面通过 Ajax 加载其所有内容,而 BS 不处理。乍一看,我认为您需要解析来自 stScript.setAttribute('data-storyid', ...); 的值并构建正确的 URL 以获取该 JSON - 或者开始使用 selenium。

标签: python web-scraping beautifulsoup visibility hidden


【解决方案1】:

问题是您想要的内容是在页面加载后由 javascript 创建的。 BeautifulSoup 无法通过 requests 库解析该内容。幸运的是,您可以结合使用 Selenium 库和 PhantomJS 来获取完全渲染的数据,然后使用 BeautifulSoup 解析生成的(完成的)html。

以下是在您的情况下的工作方式:

from bs4 import BeautifulSoup
from selenium import webdriver

site = "http://www.fifa.com/worldcup/stories/y=2017/m=11/news=australia-2921204.html#World_Cup_History"
browser = webdriver.PhantomJS()
browser.get(site)
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
print(soup.prettify())

这应该可以解决您的问题。

请注意,您必须安装一些东西,包括 selenium pip install selenium 和 PhantomJS 网络驱动程序(可从 http://phantomjs.org/download.html 下载——您可能需要将其添加到系统路径中,具体取决于您的安装方式。我为此使用了SO answer。)

【讨论】:

  • 这很奇怪。我仍然得到相同的已解析 html,它隐藏了 span 标签的信息。我遇到了一个警告 - 不确定这是否应该是一个问题:warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless...
  • PhantomJS 在 Python 2.7 上使用 Selenium v​​3.12.0 为我工作。如果您想使用无头 chrome 浏览器,那也可以。 intoli.com/blog/running-selenium-with-headless-chrome
猜你喜欢
  • 2015-05-25
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2019-12-30
  • 2021-05-13
  • 2020-06-08
  • 1970-01-01
相关资源
最近更新 更多