缺少Cookie的某些部分使用请求.get()?

2024-10-01 07:15:28 发布

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

背景信息:

I am scraping amazon. I need to set up the session cookies before using requests.session.get() to get the final version of the page source code of a url.

代码:

import requests

# I am currently working in China, so it's cn. 
# Use the homepage to get cookies. Then use it later to scrape data.
homepage = 'http://www.amazon.cn'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'}
response = requests.get(homepage,headers = headers)
cookies = response.cookies

#set up the Session object, so as to preserve the cookies between requests.
session = requests.Session()
session.headers = headers
session.cookies = cookies

#now begin download the source code
url = 'https://www.amazon.cn/TCL-%E7%8E%8B%E7%89%8C-L65C2-CUDG-65%E8%8B%B1%E5%AF%B8-%E6%96%B0%E7%9A%84HDR%E6%8A%80%E6%9C%AF-%E5%85%A8%E6%96%B0%E7%9A%84%E9%87%8F%E5%AD%90%E7%82%B9%E6%8A%80%E6%9C%AF-%E9%BB%91%E8%89%B2/dp/B01FXB0ZG4/ref=sr_1_2?ie=UTF8&qid=1476165637&sr=8-2&keywords=L65C2-CUDG'
response = session.get(url)

期望结果:

在Chrome中导航到amazon主页时,cookies应该类似于:

Amazon HomePage

正如你可以在cookies部分找到的,我用红色下划线表示,对主页请求的响应所设置的cookie的一部分是“ubid acbcn”,它也是请求头的一部分,可能是上次访问时留下的。在

这就是我想要的cookie,我试图通过上面的代码得到它。在

在python代码中,它应该是一个cookieJar或字典。不管怎样,它的内容应该包含'ubid-acbcn'和'session id'

^{pr2}$

我得到的是: “会话id”已存在,但缺少“ubid acbcn”。在

>>homepage = 'http://www.amazon.cn'
>>headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'}
>>response = requests.get(homepage,headers = headers)
>>cookies = response.cookies
>>print(cookies.get_dict()):
>>{'session-id': '456-2975694-3270026','otherparts':'otherparts'}

相关信息:

  • 操作系统:WINDOWS 10
  • PYTHON:3.5
  • 要求:2.11.1

我很抱歉有点冗长。在

我试了想:

  1. 我在谷歌上搜索了一些关键词,但似乎没有人面对这个问题 问题。在
  2. 我想这可能和亚马逊有关 防刮措施。但除了把我的头改成伪装 作为一个人,我知道我应该做的不多。在
  3. 我还考虑到,这可能不是一个失踪的饼干案件。但是我还没有建立请求.get(homepage,headers=headers)正确,因此响应.cookie与预期不符。鉴于此,我尝试在我的浏览器中复制请求头,只删除了cookie部分,但是响应cookie仍然缺少'ubid acbcn'部分。可能需要设置其他参数?在

Tags: thetourlamazongetcookieresponsesession
1条回答
网友
1楼 · 发布于 2024-10-01 07:15:28

您试图从简单的“无名”GET请求中获取cookies。但是如果“代表”Session发送它,您可以得到所需的ubid-acbcn值:

session = requests.Session()
homepage = 'http://www.amazon.cn'
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'}
response = session.get(homepage,headers = headers)
cookies = response.cookies
print(cookies.get_dict())

输出:

^{pr2}$

相关问题 更多 >