BackgroundInfo:
我正在刮亚马逊。我需要在使用requests.session.get()之前设置会话cookie,以获取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部分中找到的那样,我用红色下划线,响应我们对主页的请求设置的部分cookie是“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'}
相关信息:
我很抱歉有点啰嗦。
我尝试和想象的是:
答案 0 :(得分:0)
您正试图从简单的"无名的" GET
请求。但是如果要代表他们发送#34; 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' ...}
答案 1 :(得分:0)
所设置的cookie来自其他页面/资源,可能是由JavaScript代码加载的。因此,您可能需要使用硒Web驱动程序。查看链接以进行详细讨论。