使用Twill从登录页面Python获取.txt
我正在使用Twill检索包含所需.txt数据的页面,以便将其存储为Excel文件。数据受密码保护,因此我从使用Twill从登录页面Python获取.txt,python,python-2.7,login,twill,Python,Python 2.7,Login,Twill,我正在使用Twill检索包含所需.txt数据的页面,以便将其存储为Excel文件。数据受密码保护,因此我从/user/login页面登录 我的代码遇到了这样的问题:它试图从登录屏幕访问文本页面,并撞上了HTML的砖墙,而不是.txt本身 当我运行登录时: path = "https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/" end = "td.txt" go("http://www.naturalgasintel.com
/user/login
页面登录
我的代码遇到了这样的问题:它试图从登录屏幕访问文本页面,并撞上了HTML的砖墙,而不是.txt本身
当我运行登录时:
path = "https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/"
end = "td.txt"
go("http://www.naturalgasintel.com/user/login")
showforms()
fv("2", "user[email]", user_email)
fv("2", "user[password]", user_password)
fv("2", "commit", "Login")
datafilelocation = path + year + "/" + month + "/" + date + end
go(datafilelocation)
当我的代码到达go(datafilelocation)
==> at https://www.naturalgasintel.com/user/login?referer=%2Fext%2Fresources%2FData-Feed%2FDaily-GPI%2F2018%2F12%2F20181221td.txt
Out[18]: u'https://www.naturalgasintel.com/user/login?referer=%2Fext%2Fresources%2FData-Feed%2FDaily-GPI%2F2018%2F12%2F20181221td.txt'
因此,当我真的想进入页面时,它指向的是referer
,而不是实际的文本:
https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2018/12/20181221td.txt
我之所以使用fv(“2”,“提交”,“登录”)
而不是submit()
,是因为当我进入页面时,它会告诉我:
showforms()
然后在我submit()
之后它会告诉我:
解决此问题的最佳解决方案是什么?如果您可以使用Mechanize而不是Twill,请尝试以下方法:
导入机械化
username=“”
password=“”
登录\发布\ url=”http://www.naturalgasintel.com/user/login"
内部url=”https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2018/12/20181221td.txt"
browser=mechanize.browser()
browser.open(登录\发布\ url)
浏览器。选择表格(nr=1)
browser.form['user[email]']=用户名
browser.form['user[password]']=密码
browser.submit()
响应=browser.open(内部url)
print response.read()
问题肯定是您没有正确登录,因此当您请求数据时,它会将您重定向回/user/login
。它将url传递到referer
参数中的数据,以便在您登录后将您重定向回该url。我试图通过从主页登录来更正此问题,但如果您尝试,则只有表单#1存在,没有指向用户电子邮件或密码的指针。它只提供快速搜索页面,因此我必须从用户/登录页面登录。有没有办法登录、使用cookies保存并返回主页访问该文件?谢谢,@walkinghawk。这真的是2.7版本中的唯一方法!
Form name=quick-search (#1)
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 q text q Search
Form #2
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 utf8 hidden (None) ✓
2 authenticity_token hidden (None) pnFnPGhMomX2Lyh7/U8iGOZKsiQnyicj7BWT ...
3 referer hidden (None) https://www.naturalgasintel.com/ext/ ...
4 popup hidden (None) false
5 user[email] text user_email
6 user[password] password user_pas ...
7 user[remember_me] hidden (None) 0
8 user[remember_me] checkbox user_rem ... None
9 commit submit (None) Login
Note: submit is using submit button: name="commit", value="Login"