【发布时间】:2018-04-16 22:54:58
【问题描述】:
我想用 Python 登录 Amazon.com。 但即使我使用 requests.Session() 也做不到,因为我不能“启用 Cookie”。
您能告诉我如何修复代码吗?为什么“dict(response.cookies)”返回空?
# creating all input tag information (hidden tags are included)
# {'pageId': 'ape:dXNmbGV....'email': 'xxx@xxx', 'password': 'xxx', 'create': '0'}
def create_signin_data(res, user, pass) -> str:
bs = BeautifulSoup(res.content, "html.parser")
signin_data = {s["name"]: s["value"]
for s in bs.select("form[name=signIn]")[0].select("input[name]")
if s.has_attr("value")}
signin_data[u"email"] = user
signin_data[u"password"] = pass
return signin_data
signin_url ="https://www.amazon.com/ap/signin?_encoding=UTF8&........."
action_url ="https://www.amazon.com/ap/signin"
### create session
session = requests.Session()
res = session.get(signin_url)
# res = session.get(signin_url, cookies = res.cookies) -> the result is the same
cookie_data = dict(response.cookies) # empty dict {}
### sign in
signin_data = create_signin_data(res, "user@addr", "pass")
res = session.post(signin_url, signin_data)
# res = session.post(action_url, signin_data) -> the result is the same
# res = session.post(signin_url, signin_data, cookies=cookie_data ) -> the result is the same
print(res.content)
最后输出 (html) -----------------
请启用 Cookie 以继续
要继续在 Amazon.com 购物,请在您的 Web 浏览器中启用 cookie。
在您的浏览器中启用 cookie 后,请单击下面的按钮返回上一页。
我想获得登录后首页(您的 Amazon.com)
【问题讨论】:
-
为什么需要获取登录网址?如果您检查 amazon.com 中的登录表单,您会发现该表单具有操作和方法。并且,使用输入数据提交表单。
-
登录网址和操作值几乎相同。如果我运行“session.post(action_url, signin_data)”,结果 html 会显示“请启用 Cookie”
标签: python cookies web-scraping