簡體   English   中英

使用 Python Selenium 使用畫布元素抓取網站

[英]Scraping website with canvas elements using Python Selenium

我真的會使用一些幫助來從本網站上的折線圖或圓環圖上抓取數據。 我需要這些數據用於一個專注於預測荷蘭太陽能和風能生產的研究項目。

我想使用 Python 來完成這項任務,並且我曾嘗試使用 Selenium 這樣做。

數據存儲在畫布元素中,這使得這比預期的更具挑戰性,我會使用一些幫助來找出正確的方法來提取數據。 對此的任何幫助將不勝感激。

到目前為止,我的方法是找到折線圖元素,然后在圖表上從左到右“移動鼠標”(使用 Selenium Actions 和 move_to_element_with_offset 函數)。

對於每一步,我都會記錄懸停文本中可用的數據,並以某種方式將其鏈接到正確的時間戳。

有關它在我的瀏覽器中的外觀的屏幕截圖,請參見此處。 請注意懸停時 Zonne 能量數據值如何出現在下面的 div 中:

它在瀏覽器中的外觀

但是,問題是我無法接收頁面源中的數據。 可能是因為我無法弄清楚如何使用 Selenium 將鼠標懸停在圖表上。

我的初始代碼是:

chrome_driver_path = pathlib.Path(__file__).parent / "chromedriver"
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(executable_path=chrome_driver_path,options=options)
url = "https://energieopwek.nl"
driver.get(url)

line_chart=driver.find_element(By.ID,"linechart_1")
action.move_to_element(line_chart).click().perform() # clicking on the chart
soup = BeautifulSoup(driver.page_source, 'lxml')
print(soup.prettify()) # I'd expect to see the data in the page source, but it's not

這是頁面源輸出。 我希望圖表中的數據會出現在 div 中,如上面的屏幕截圖所示:

 <div _echarts_instance_="ec_1652165210746" class="eo-chart" id="linechart_1" style="-webkit-tap-highlight-color: transparent; user-select: none; position: relative; background: rgba(0, 0, 0, 0);"> <div style="position: relative; overflow: hidden; width: 744px; height: 385px; padding: 0px; margin: 0px; border-width: 0px; cursor: default;"> <canvas data-zr-dom-id="zr_0" height="385" style="position: absolute; left: 0px; top: 0px; width: 744px; height: 385px; user-select: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); padding: 0px; margin: 0px; border-width: 0px;" width="744"> </canvas> </div> <div> --- WHERE IS THE DATA?--- </div> </div>

想知道是否有人能在這里幫助我?

如果這是針對您要發布的項目,您應該聯系來源請求許可,或讓律師參與,以確保您沒有違反該網站上的服務條款。 我感覺他們可能混淆了數據以阻止您嘗試做的事情。


關於我的評論和可用的數據:
https://energieopwek.nl/data.php?sid=2ecde3&Day=2022-05-05&scale=day

即使 JS 代碼被丑化了,我們仍然可以編造一些:
... return seriesData引起了我的注意,看起來那是圖表的原始數據

如果您知道如何在作為起點的開發者控制台上使用調試

如果您喜歡使用這種方法,那么看起來有一種方法可以從 selenium 中讀取 JS 變量:
使用 Selenium WebDriver 讀取 JavaScript 變量


您可以使用 selenium 截取屏幕截圖,然后自動裁剪。 這是我以前做過的類似事情的一個例子。

element = driver.find_element_by_xpath('//*[@id="THIS_WEEK"]')
location = element.location
size = element.size
driver.save_screenshot("due.png")
x = location['x']
y = location['y']
w = size['width']
h = size['height']
width = x + w
height = y + h
im = Image.open('due.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('due.png')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM