【问题标题】:Looking to scrape a website daily and set up alerts希望每天抓取一个网站并设置警报
【发布时间】:2014-01-26 23:17:19
【问题描述】:

我需要运行一个脚本,每天抓取以下网站(当脚本运行时,它会抓取当天的日历)(相当于点击“每日”按钮)

http://www.fxempire.com/economic-calendar/

我想提取特定日期的所有日期数据/事件,并过滤相关货币(如果适用),然后在每个事件发生前 10 分钟创建某种警报或弹出.

到目前为止,我正在使用以下代码来抓取网页,然后查看/打印变量“html”,但找不到我需要的日历信息。

import sys  
from PyQt4.QtGui import *  
from PyQt4.QtCore import *  
from PyQt4.QtWebKit import *  



class Render(QWebPage):  
  def __init__(self, url):  
    self.app = QApplication(sys.argv)  
    QWebPage.__init__(self)  
    self.loadFinished.connect(self._loadFinished)  
    self.mainFrame().load(QUrl(url))  
    self.app.exec_()  

  def _loadFinished(self, result):  
    self.frame = self.mainFrame()  
    self.app.quit()  

url = 'http://www.fxempire.com/economic-calendar/'  
r = Render(url)  
html = r.frame.toHtml()  

【问题讨论】:

  • 你能告诉我们你到目前为止有什么吗?
  • 抱歉,现在已更新原始帖子以包含我尝试使用的代码

标签: python python-2.7 web-scraping


【解决方案1】:

在我看来,从网页中抓取数据的最佳方法是使用BeautifulSoup。这是一个快速脚本,可以获取您想要的数据。

import re
from urllib2 import urlopen
from bs4 import BeautifulSoup


# Get a file-like object using urllib2.urlopen
url = 'http://ecal.forexpros.com/e_cal.php?duration=daily'
html = urlopen(url)

# BS accepts a lot of different data types, so you don't have to do e.g.
# urlopen(url).read(). It accepts file-like objects, so we'll just send in html
# as a parameter.
soup = BeautifulSoup(html)

# Loop over all <tr> elements with class 'ec_bg1_tr' or 'ec_bg2_tr'
for tr in soup.find_all('tr', {'class': re.compile('ec_bg[12]_tr')}):
    # Find the event, currency and actual price by looking up <td> elements
    # with class names.
    event = tr.find('td', {'class': 'ec_td_event'}).text
    currency = tr.find('td', {'class': 'ec_td_currency'}).text
    actual = tr.find('td', {'class': 'ec_td_actual'}).text

    # The returned strings which are returned are unicode, so to print them,
    # we need to use a unicode string.
    print u'{:3}\t{:6}\t{}'.format(currency, actual, event)

为了给您一些关于如何在未来解决此类问题的提示,我已经写下了解决您的问题时使用的步骤。希望对您有所帮助。

  1. 我在 Chrome 中打开网页,右键单击并选择 Inspect Element
  2. 通过查看元素选项卡找到了包含信息的iframe,并打开了该网址。
  3. 也检查了这个页面,发现所有包含数据的元素都是&lt;tr&gt;元素,并且有ec_bg1_trec_bg2_tr类。
  4. 我从之前与 BS 的接触中知道,它可以使用 soup.find_all('tr', {'class': 'ec_bg1_tr'}) 找到所有类 ec_bg1_trtr 元素。我最初的想法是首先遍历这些元素,然后遍历 ec_bg2_tr 元素。
  5. 然后我想也许 BS 足够聪明,可以接受正则表达式作为输入,所以我检查了他们的 docs,看起来这应该不是问题。
  6. 按照文档中的方法,然后我尝试使用简单的正则表达式 'ec_bg_[12]_tr'。
  7. Ca-ching!

【讨论】:

  • 这是一个非常好的解决方案,我现在正在使用它进行基本分析,我还有其他工具,例如 ystockquote python 库,我将它与我的一些代码一起用于对我的股票进行一些技术分析!这很好,可以最大限度地自定义@ Steinar Lima。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多