首页 > 解决方案 > 有人可以帮我从名为 Suncalc.org 的网站获取实时数据吗

问题描述

我使用 beautifulsoup 从这个网站获取数据。我的代码:

import bs4
import requests
from bs4 import BeautifulSoup

r = requests.get('https://www.suncalc.org/#/12.98,80.188,10/2020.02.21/15:51/1/3')
soup = BeautifulSoup(r.content,'html.parser')
week = soup.find(id='clickSunrise')

print(week)

结果:

<span class="sunriseX Bold sunrise-time" id="clickSunrise" style="white-space:nowrap;">...</span>

那三个点实际上是数字,我需要这些数字。

标签: pythonweb-scrapingbeautifulsoup

解决方案


您好,我测试了您的代码,似乎网站在浏览器请求信息之前不会加载数据。由于您使用的是请求模块,因此没有浏览器。

您需要使用像 selenium 模块这样的浏览器模拟器来获取该数据。该模块将为您打开一个浏览器,您可以对其进行编程以导航到该网站,等待所有内容加载并为您获取信息。

脚步:

1-安装硒

2-下载 chromedriver 并将其放在某处(可能在您的项目中)

https://chromedriver.chromium.org/downloads

3-Learn selenium(这是一个自动导航网络的神奇工具)。这是一个未经测试的示例,只是为了让您有一个想法(可能会立即为您工作,但可能不会)

import time
from selenium import webdriver

driver = webdriver.Chrome('/path/to/chromedriver')  # Change this to your chromedriver path.

driver.get('https://www.suncalc.org/#/12.98,80.188,10/2020.02.21/15:51/1/3');
time.sleep(5) # Let the user actually see something!
clickSunrise = driver.find_element_by_id('clickSunrise')
print(clickSunrise.text)

我希望这有帮助!


推荐阅读