背景信息:
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 中导航到亚马逊主页时,cookie 应该类似于:
正如你在我用红色下划线的cookies部分可以发现的,我们对主页的请求的响应设置的cookies的一部分是“ubid-acbcn”,这也是请求头的一部分,可能是留下的自上次访问以来。
这就是我想要的 cookie,我尝试通过上面的代码获取它。
在Python代码中,它应该是一个cookieJar,或者一个字典。无论哪种方式,其内容都应该包含'ubid-acbcn'和'session-id':
{'ubid-acbcn':'453-7613662-1073007','session-id':'455-1363863-7141553','otherparts':'otherparts'}
我得到了什么: “session-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
很抱歉说得有点啰嗦。
我尝试并计算出的结果:
- 我在谷歌上搜索了某些关键字,但似乎没有人遇到这个问题 问题。
- 我认为这可能与亚马逊有关 防刮措施。但除了改变我的标题来伪装 作为一个人,我知道自己应该做的事情并不多。
- 我也考虑到这可能不是缺少 cookie 的情况。但我没有正确设置 requests.get(homepage,headers = headers) ,因此 response.cookie 不符合预期。鉴于此,我尝试在浏览器中复制请求 header ,只保留 cookie 部分,但响应 cookie 仍然缺少“ubid-acbcn”部分。也许还需要设置一些其他参数?
最佳答案
您正在尝试从简单的“无名”GET
请求中获取 cookie。但是,如果“代表”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())
输出:
{'ubid-acbcn': '456-2652288-5841140' ...}
关于python - 使用 requests.get() 时缺少 Cookie 的某些部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41156339/