如何用Python实现实时流式数据采集?

2024-05-06 11:09:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图为这个网页抓取航班数https://www.flightradar24.com/56.16,-49.51

数字在下图中突出显示: enter image description here

数字每8秒更新一次。

这就是我试过的美组:

import requests
from bs4 import BeautifulSoup
import time

r=requests.get("https://www.flightradar24.com/56.16,-49.51")
c=r.content
soup=BeautifulSoup(c,"html.parser")
value=soup.find_all("span",{"class":"choiceValue"})
print(value)

但它总是返回0:

[<span class="choiceValue" id="menuPlanesValue">0</span>]

View source也显示0,所以我理解为什么BeautifulSoup也返回0。

有没有人知道其他方法来得到当前值?


Tags: httpsimportcom网页valuewww数字requests
3条回答

因此,根据@Andre发现的情况,我编写了以下代码:

import requests
from bs4 import BeautifulSoup
import time

def get_count():
    url = "https://data-live.flightradar24.com/zones/fcgi/feed.js?bounds=59.09,52.64,-58.77,-47.71&faa=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&maxage=7200&gliders=1&stats=1"

    # Request with fake header, otherwise you will get an 403 HTTP error
    r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})

    # Parse the JSON
    data = r.json()
    counter = 0

    # Iterate over the elements to get the number of total flights
    for element in data["stats"]["total"]:
        counter += data["stats"]["total"][element]

    return counter

while True:
    print(get_count())
    time.sleep(8)

代码应该是自我解释的,它所做的一切就是每8秒打印一次实际的航班计数:)

注意:这些值与网站上的值相似,但不相同。这是因为Python脚本和网站不太可能同时发送请求。如果你想得到更准确的结果,例如每4秒就要发出一个请求。

你想用什么就用什么,扩展什么。希望这有帮助!

这种方法的问题在于,页面首先加载视图,然后执行常规请求以刷新页面。如果您在Chrome中查看开发人员控制台中的network选项卡(例如),您将看到对https://data-live.flightradar24.com/zones/fcgi/feed.js?bounds=59.09,52.64,-58.77,-47.71&faa=1&mlat=1&flarm=1&adsb=1&gnd=1&air=1&vehicles=1&estimated=1&maxage=7200&gliders=1&stats=1的请求

响应是常规json:

{
  "full_count": 11879,
  "version": 4,
  "afefdca": [
    "A86AB5",
    56.4288,
    -56.0721,
    233,
    38000,
    420,
    "0000",
    "T-F5M",
    "B763",
    "N641UA",
    1473852497,
    "LHR",
    "ORD",
    "UA929",
    0,
    0,
    "UAL929",
    0
  ],
  ...
  "aff19d9": [
    "A12F78",
    56.3235,
    -49.3597,
    251,
    36000,
    436,
    "0000",
    "F-EST",
    "B752",
    "N176AA",
    1473852497,
    "DUB",
    "JFK",
    "AA291",
    0,
    0,
    "AAL291",
    0
  ],
  "stats": {
    "total": {
      "ads-b": 8521,
      "mlat": 2045,
      "faa": 598,
      "flarm": 152,
      "estimated": 464
    },
    "visible": {
      "ads-b": 0,
      "mlat": 0,
      "faa": 6,
      "flarm": 0,
      "estimated": 3
    }
  }
}

我不确定这个API是否以任何方式受到保护,但似乎我可以使用curl访问它而不会有任何问题。

更多信息:

您可以使用selenium对包含由javascript添加的动态内容的网页进行爬网。

from bs4 import BeautifulSoup
from selenium import webdriver

browser = webdriver.PhantomJS()
browser.get('https://www.flightradar24.com/56.16,-49.51/3')

soup = BeautifulSoup(browser.page_source, "html.parser")
result = soup.find_all("span", {"id": "menuPlanesValue"})

for item in result:
    print(item.text)

browser.quit()

相关问题 更多 >