在Python

时间:2018-03-04 13:19:19

标签: python html web-scraping

我已经按照在线教程进行了操作,并成功创建了一个与逐步跟踪相同的网络刮刀。

但是,当我尝试在我想要的网站上实现此代码时,我的控制台上将返回所有空白数据。我希望有人可以看一下我收集的短代码来收集数据,看看我是否已经正确地完成了这项工作,或者我不知道网站上的某些协议不允许从中删除数据。< / p>

# import libraries
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup 

myurl = "http://smartgriddashboard.eirgrid.com/#all/generation"

# opening up connection, grabbing the page
uClient = uReq(myurl)
page_html = uClient.read()
uClient.close()

# html parsing
page_soup = soup(page_html, "html.parser")

# find the data of interest
key_stats = page_soup.findAll("div",{"class":"key-stats-container"})

然后我尝试调用key_stats,所有出现的都是[]。正如我之前所说,当在在线教程的示例网页上执行此操作时,该类中的所有数据都已存储。

我不是专业的程序员,所有这一切对我来说都是新的,所以任何和所有的帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

问题是您尝试从页面中抓取的div是使用Javascript动态生成的。它不在HTML source code中,这意味着urllib.request无法访问该信息。当您在浏览器中加载页面时,您应该注意到该信息不会立即出现在屏幕上,统计信息会在页面加载后几秒钟出现。

您可以尝试查看网站的Javascript或源文件,并尝试find where the information is coming from(通常是JSON或XML文件),或使用类似selenium(自动浏览器)的内容在页面上的相关元素之后解析页面:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()

try:
    driver.get("http://smartgriddashboard.eirgrid.com/#all/generation") # load the page
    WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.key-stats-container > .stat-box'))) # wait till relevant elements are on the page
except:
    driver.quit() # quit if there was an error getting the page or we've waited 15 seconds and the stats haven't appeared.
stat_elements = driver.find_elements_by_css_selector('.key-stats-container > .stat-box')
for el in stat_elements: 
    print(el.find_element_by_css_selector('label').text)
    print(el.find_element_by_css_selector('p').text)
driver.quit()                                      

WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.key-stats-container > .stat-box')))将等待15秒或until它会在超时之前通过css选择器找到一个元素,您可以根据需要更改15秒。

我没有等待.key-stats-container,而是等待.key-stats-container > .stat-box(一个类stats-box的元素,它是.key-stats-container的直接子元素),因为有一点.key-stats-container已加载,但统计数据没有:

   <span class="load"></span>
    <div class="error-msg">
        <p>We had some trouble gathering the data.</p>
        <p>Refresh to try again.</p>
    </div>
</div>

这是输出:

LATEST SYSTEM
GENERATION
4,885 MW
THERMAL GENERATION
(COAL, GAS, OTHER)
56.81 %
RENEWABLE
GENERATION
43.03 %
NET
IMPORT
0.16 %