使用python请求的etrade抓取不希望使用跨域url

2024-05-15 00:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试从etrade获取一些基本的股票信息(我知道他们有一个api,但我想先弄清楚这个问题),然后我可以使用请求模块通过以下登录:

import requests
from bs4 import BeautifulSoup, Comment
symbol = 'A'
payload = {'USER':etradeUsername, 'PASSWORD':etradePassword, 'countrylangselect':'us_english', 'TARGET':'/e/t/pfm/portfolioview'}
with requests.Session() as c:
    c.post('https://us.etrade.com/login.fcc', data=payload)
    r=c.get('https://us.etrade.com/e/t/pfm/portfolioview')
    #r=c.get('https://www.etrade.wallst.com/v1/stocks/snapshot/snapshot.asp?symbol=' + symbol + '&rsO=new')

    etradeMarkup = BeautifulSoup(r.text)
    #print r.headers
    file1 = open("etrade.html","w")
    file1.write("<html><body><head><meta charset='UTF-8'></head>" + str(etradeMarkup.prettify().encode("utf-8")) + "</body></html>")
    file1.flush()
    file1.close()

写文件是为了让我看看刮刀能得到什么。在

我可以看到公文包页面,所以我知道登录是有效的。下一行被注释掉的是我的目标页面。我能看到www.etrade.wallst.com。。。页面后,成功登录我的浏览器,但刮板刚刚被重定向到etrade.com网站登录页面。在

我认为有一个会话传输或cookie变量在域之间移动,我的浏览器知道如何处理,但我的代码却不知道

我对python和http的知识已经到了死胡同了,我希望有人能为我指出正确的方向,以找出如何通过编程克服这个困难。在

非常感谢你能提供的任何帮助。 (对python和scraping不熟悉,所以请友好点:)


Tags: httpsimportcomgethtml页面symbolrequests
1条回答
网友
1楼 · 发布于 2024-05-15 00:24:55

我发现还有另一个页面需要设置cookies。我以为推送到etrade登录页面是因为需要etrade登录后部分的cookies,但我错了。我根本不需要这个页面的etrade登录,只需要另一个页面来获取cookies。通过添加视图https://us.etrade.com/e/t/invest/markets?ploc=c-MainNav的行,我能够获得查看目标页面所需的数据,而不会迫使我的程序返回登录页面。在

with requests.Session() as c:

    #  adding this line was the key
    c.get('https://us.etrade.com/e/t/invest/markets?ploc=c-MainNav') 

    r=c.get('https://www.etrade.wallst.com/v1/stocks/snapshot/snapshot.asp?symbol=' + symbol + '&rsO=new')

    etradeMarkup = BeautifulSoup(r.text)

相关问题 更多 >

    热门问题