我使用Twill检索包含wanted.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")
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)
时,我得到了:
所以当我真正想进入页面时,它指向的是referer
,而不是实际的文本:
https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2018/12/20181221td.txt
我使用fv("2", "commit", "Login")
而不是submit()
的原因是,当我到达页面时,它会给出以下信息:
showforms()
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
然后在我submit()
之后告诉我:
Note: submit is using submit button: name="commit", value="Login"
解决这个问题最好的办法是什么?在
如果使用Mechanize而不是Twill可以,请尝试以下方法:
import mechanize username = "" password = "" login_post_url = "http://www.naturalgasintel.com/user/login" internal_url = "https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2018/12/20181221td.txt" browser = mechanize.Browser() browser.open(login_post_url) browser.select_form(nr = 1) browser.form['user[email]'] = username browser.form['user[password]'] = password browser.submit() response = browser.open(internal_url) print response.read()
;