【问题标题】:Scrape data in script tag抓取脚本标签中的数据
【发布时间】:2019-10-19 11:15:55
【问题描述】:

任何人都可以提出一种方法来抓取<script> 标记中的数据,特别是在本例中是来自 AEMO (https://www.aemo.com.au/aemo/apps/visualisations/elec-nem-priceanddemand.html) 的 30 分钟表。

要获取数据表,我需要单击在网站上显示表的按钮或下载按钮。但是,这里的障碍是,当我尝试使用 Selenium 抓取它时,表格的按钮和文本隐藏在 <script> 标签后面。

到目前为止,这是我的代码:

# import libraries
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

url = "https://www.aemo.com.au/aemo/apps/visualisations/elec-nem-priceanddemand.html"
browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')
browser.get(url)
try:
    print(browser.page_source)
except:
    print("not found")
finally:
    browser.quit()

部分结果是:

<body aurelia-app="visualisation-main" data-gr-c-s-loaded="true">
    <div class="splash">
      <div class="message"><span class="icon-spinner"></span></div>
    </div>

    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script>
      System.import('aurelia-bootstrapper');
    </script>


</body></html>

【问题讨论】:

    标签: javascript python selenium-webdriver scrape


    【解决方案1】:

    Selenium 有自己的定位元素的方法,例如find_element_by_css_selector。很多时候,浏览器需要一些时间来渲染元素,所以你可能需要使用WebdriverWait

    以下是从页面中提取现货价格的示例:

    from selenium import webdriver
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    
    url = 'https://www.aemo.com.au/aemo/apps/visualisations/elec-nem-priceanddemand.html'
    
    browser = webdriver.Chrome()
    browser.get(url)
    
    sel = 'body > div > compose > div > compose.fill-height.flex-container.au-target > compose > div > div:nth-child(1) > div'
    element = WebDriverWait(browser, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, sel))
    )
    
    print(element.text)
    

    结果

    $92.02/MWh
    

    【讨论】:

      猜你喜欢
      • 2020-12-29
      • 1970-01-01
      • 2020-06-18
      • 2021-10-15
      • 2021-01-09
      • 2020-04-05
      • 2013-07-12
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多