首页 > 解决方案 > 登录网站以使用 Python 访问数据

问题描述

我订阅了该网站https://www.naturalgasintel.com/的每日数据源,这些数据直接以 .txt 文件形式显示在他们的网站上;他们的用户登录页面是https://www.naturalgasintel.com/user/login/

例如,今天的提要文件由链接给出,https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2019/01/20190104td.txt并显示在网站上,如下图所示:

在此处输入图像描述

我想做的是使用我的user_email和登录user_password并以 Excel 文件的形式抓取这些数据。

当我Twill通过首先将我登录到网站来尝试“指向”我的数据时,我使用以下代码:

from email.mime.text import MIMEText
from subprocess import Popen, PIPE
import twill
from twill.commands import *

year= NOW[0:4]
month=NOW[5:7]
day=NOW[8:10]
date=(year+month+day)

path = "https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/"
end = "td.txt"

go("http://www.naturalgasintel.com/user/login")
fv("2", "user[email]", user_email)
fv("2", "user[password]", user_password)
fv("2", "commit", "Login")

datafilelocation = path + year + "/" + month + "/" + date + end
go(datafilelocation)

但是,当我转到数据的位置时,从用户登录页面登录会将我发送到此引用链接。

https://www.naturalgasintel.com/user/login?referer=%2Fext%2Fresources%2FData-Feed%2FDaily-GPI%2F2019%2F01%2F20190104td.txt

而不是:

https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2019/01/20190104td.txt

我也尝试过使用类似requests的模块从站点登录,然后访问这些数据,但是无论我使用什么方法都会将我发送到 HTML 源而不是 .txt 数据位置本身。

我已经发布了我对 Python 2.7 模块的完整演练Twill,我在此处附上了赏金

使用斜纹从登录页面 Python 抓取 .txt

能够访问这些受密码保护的文件的最佳解决方案是什么?

标签: pythonpython-3.xpython-2.7urlpython-requests

解决方案


如果您有兼容的 FireFox 版本,请获取 Chee 的插件 javascript 0.0.1 并添加以下内容以在页面上运行:

document.getElementById('user_email').value = "E-What";
document.getElementById('user_password').value = " ABC Password ";

根据需要更改电子邮件和密码。它将加载页面,然后输入您的用户名和密码。

还有其他方法可以通过您自己的独立流程自行完成所有操作。如果您以这种方式更改它,您不必下载其他人的程序并尝试学习它们(除了这个小东西)。

我会投票赞成这个问题。


推荐阅读