我想从运行在 ubuntu 服务器上的脚本登录到我的雅虎帐户。我曾尝试将 python 与 mechanize 一起使用,但我的计划存在缺陷。
这是我目前拥有的代码。
loginurl = "https://login.yahoo.com/config/login"
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
r = br.open(loginurl)
html = r.read()
br.select_form(nr=0)
br.form['login']='[mylogin]'
br.form['passwd']='[mypassword]'
br.submit()
print br.response().read()
我得到的响应是一个带有粗体红色文本的雅虎登录页面。“必须在您的浏览器上启用 Javascript”或类似内容。mechanize docs 上有一个部分提到了使用 JS 创建 cookie 的页面,但是帮助页面返回 HTTP 400(只是我的运气)
弄清楚 javascript 做了什么,然后手动执行,这听起来是一项非常困难的任务。我非常愿意切换到任何工具/语言,只要它可以在 ubuntu 服务器上运行。即使这意味着使用不同的登录工具,然后将登录 cookie 传递回我的 python 脚本。任何帮助/建议表示赞赏。
更新:
我不想使用 Yahoo API
我也尝试过使用scrapy,但我认为会出现同样的问题
我的scrapy脚本
class YahooSpider(BaseSpider):
name = "yahoo"
start_urls = [
"https://login.yahoo.com/config/login?.intl=us&.lang=en-US&.partner=&.last=&.src=&.pd=_ver%3D0%26c%3D%26ivt%3D%26sg%3D&pkg=&stepid=&.done=http%3a//my.yahoo.com"
]
def parse(self, response):
x = HtmlXPathSelector(response)
print x.select("//input/@value").extract()
return [FormRequest.from_response(response,
formdata={'login': '[my username]', 'passwd': '[mypassword]'},
callback=self.after_login)]
def after_login(self, response):
# check login succeed before going on
if response.url == 'http://my.yahoo.com':
return Request("[where i want to go next]",
callback=self.next_page, errback=self.error, dont_filter=True)
else:
print response.url
self.log("Login failed.", level=log.CRITICAL)
def next_page(sekf, response):
x = HtmlXPathSelector(response)
print x.select("//title/text()").extract()
scrapy 脚本只输出“https://login.yahoo.com/config/login”......嘘