无法使用请求模拟浏览器行为

时间:2016-02-01 01:12:16

标签: python selenium-webdriver python-requests

我正在尝试向网站发送帖子请求以获得json响应。当我点击链接时,我可以在Chrome Inspector中看到json响应,但我可以使用请求获取它。 首先,我尝试使用请求Session来获取cookie并在发布请求中使用它们,但无济于事。

session = requests.Session()
session.get('http://www.auchandrive.fr/drive/pagestatique.pagetemplate.popuphandler.popinchangementmagasin.changermag/537?t:ac=PAGE_STATIQUE_ENGAGEMENTS')
response = session.post('http://www.auchandrive.fr/drive/rayon.productlist.pagination_0.topage/1?t:ac=3686973/3686997')
print response.text

其次我使用Selenium + PhantomJS获取cookie并在请求中使用它们,没有结果!

browser = webdriver.PhantomJS(PHANTOMJS_PATH)
browser.get('http://www.auchandrive.fr/drive/pagestatique.pagetemplate.popuphandler.popinchangementmagasin.changermag/537?t:ac=PAGE_STATIQUE_ENGAGEMENTS')
all_cookie = {}
for cookie in browser.get_cookies():
    all_cookie[cookie['name']] = cookie['value']
rep = requests.post('http://www.auchandrive.fr/drive/rayon.productlist.pagination_0.topage/1?t:ac=3686973/3686997', cookies=all_cookie)

仅当我从Chrome手动获取Cookie时才有效。 我看不出有什么问题!

1 个答案:

答案 0 :(得分:0)

session = requests.Session()
session.get('http://www.auchandrive.fr/drive/pagestatique.pagetemplate.popuphandler.popinchangementmagasin.changermag/537?t:ac=PAGE_STATIQUE_ENGAGEMENTS')
response = session.post('http://www.auchandrive.fr/drive/rayon.productlist.pagination_0.topage/1?t:ac=3686973/3686997')
print(response.json)

使用json属性将获取JSON响应。您还可以使用请求进行持久会话,因此提供了cookie。

response.cookies #The cookies attribute
相关问题