我计划从可用的开放网络中检索历史数据。从链接:
https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day
理想情况下,我试图使用来自 Pandas 数据框的输入来更改国家/地区、日、月、年,并检索结果(此网页中的能源消耗)并将其存储回 excel。
我正在尝试使用不同的网络抓取工具,并且有一项信息对我的可能性表示怀疑。
它是:当我手动更改国家、日、月、年和检索结果时,网页链接保持不变。是否有可能通过此 Web 链接实现我的目标。
感谢您的时间。
最佳答案
首先,您需要了解单击“发送”按钮时会发生什么。 POST 请求被发送到同一个 URL,其参数与您在表单上选择的值相对应。您可以在浏览器开发人员工具 - “网络”选项卡中看到此请求。现在,你需要在你的代码中模拟这个请求(我将使用下面的很棒的 requests
package)
另一个问题是,如果您检查对该 POST 请求的响应中得到的内容,您将找不到相同的 table
具有所需数据的元素,就像您在浏览器中看到的那样。这是因为 table
从 myData
动态生成javascript 变量“坐在”上 script
元素。由于也没有 BeautifiulSoup
,也不是 requests
是浏览器,不能执行JavaScript,需要解压myData
脚本中的值。
这是一个工作代码,可以让您在 01/01/2009 的“归档”范围内获得所需的数据:
import re
from ast import literal_eval
from pprint import pprint
import requests
from bs4 import BeautifulSoup
url = "https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day"
data = {
"opt_period": "2",
"opt_Country": "3",
"opt_Day": "1",
"opt_Month": "1",
"opt_Year": "2009",
"opt_Response": "1",
"send": "send"
}
with requests.Session() as session:
session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'}
# visit the page
session.get(url)
# make a POST request
response = session.post(url, data=data)
soup = BeautifulSoup(response.content, 'html.parser')
# find the desired script
pattern = re.compile(r"var myData = (.*?);", re.MULTILINE | re.DOTALL)
script = soup.find("script", text=pattern)
# extract the data from the script
match = pattern.search(script.get_text())
data = match.group(1).strip()
data = literal_eval(data)
pprint(data)
打印列表的 Python 列表:
[['AT',
'2009-01-01',
6277,
6002,
5649,
5230,
5034,
5038,
4858,
5127,
5342,
5747,
6100,
6373,
6325,
6210,
6129,
6160,
6588,
7007,
7058,
6887,
6586,
6137,
6494,
5974]]
关于python - 使用 Python 进行网页抓取 - 链接与表单输入保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901841/