首页 > 解决方案 > Python 请求输出与预期输出不同

问题描述

我正在尝试从以下站点中删除 Generation 表。

我有以下代码:

import requests
from bs4 import BeautifulSoup

source = requests.get('http://reneweconomy.com.au/nem-watch/', headers={'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(source.text, 'html.parser')

table = soup.table["database table"].strip()
print(table)

但是,此代码无法在抓取的页面中找到任何表格,即使在查看检查时它明显存在。 检查 这可能是网站无法正确抓取的问题吗?

谢谢

标签: pythonpython-requests

解决方案


此页面用于JavaScript加载数据和创建表。

在 Firefox/Chrome 中使用DevTools我发现它是从

https://ausrealtimefueltype.global-roam.com/api/SeriesSnapshot?time=

作为 JSON 数据


import requests

headers = {'User-Agent': 'Mozilla/5.0'}

url = 'https://ausrealtimefueltype.global-roam.com/api/SeriesSnapshot?time='

r = requests.get(url,  headers=headers)
data = r.json()

for item in data['seriesCollection']:
    #for key, value in item.items():
    #    print(key, value)
    print('region:', item['metadata']['region']['name'])
    print('fuel type:', item['metadata']['fuelType']['name'])
    print('value:', item['value'])
    print('---')

结果

region: Queensland
fuel type: Black Coal
value: 5536.51307
---
region: Queensland
fuel type: Gas
value: 560.24621
---
region: Queensland
fuel type: Liquid Fuel
value: 0.0
---
region: Queensland
fuel type: Other
value: 23.9
---
region: Queensland
fuel type: Hydro
value: 18.415
---

# etc.

推荐阅读