我正尝试从一个电力数据网站收集一个数据点:
到目前为止,我已经编写了以下代码:
from requests_html import HTMLSession #import libraries
s = HTMLSession()
url = 'https://app.electricitymap.org/zone/DK-DK2'
r = s.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'})
webpageTitle = (r.html.find('title', first=True).text)
print(webpageTitle)我可以得到VS代码打印标题的网站,但我只感兴趣的可再生能源的数量在给定的时刻。这将显示为网站左上角的“可再生”拨号。
我已经检查了网站,并发现了我想收集的价值:铬DevTools的截图。
我需要写什么才能在Python中打印这个值?
发布于 2022-03-21 23:37:27
正如@ through所言,该网站完全是通过Javascrip构建的。我测试了requests_html和selenium。requests_html给出了空的outupt含义,不能渲染JavaScript,但是selenium产生了完美的输出。
from requests_html import HTMLSession #import libraries
from bs4 import BeautifulSoup as bs
s = HTMLSession()
url = 'https://app.electricitymap.org/zone/DK-DK2'
r = s.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'})
soup=bs(r.text,'html.parser')
renewable=[x.get_text() for x in soup.select('g[class="circular-gauge"] text')]
print(renewable)输出:
[]
#Selenium: You have nothing to install just you can run the code
from bs4 import BeautifulSoup as bs
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
url = 'https://app.electricitymap.org/zone/DK-DK2'
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
driver.get(url)
time.sleep(2)
soup=bs(driver.page_source,'html.parser')
renewable=[x.get_text() for x in soup.select('g[class="circular-gauge"] text')][1]
print(renewable)输出:
69%https://stackoverflow.com/questions/71564953
复制相似问题