【问题标题】:What is the correct format for sending cookies in a post request with Python Requests?使用 Python 请求在 post 请求中发送 cookie 的正确格式是什么?
【发布时间】:2019-04-09 09:41:49
【问题描述】:

我想在使用 BS4 解析 URL 之前将 cookie 设置为 URL。首先,我不确定我是否使用了正确的 cookie 格式。以下是它们在 chrome DevTool 中的样子:

  • 名称:aep_usuc_f
  • 价值:site=rus&c_tp=USD&region=IE&b_locale=ru_RU

这是我的代码:

url = 'https://example.com/item/123.html'
cookies = {'aep_usuc_f': 'site=rus&c_tp=USD&region=IE&b_locale=ru_RU'}

s = requests.Session()
s.post('https://example.com/item/123.html', cookies=cookies)
r = s.get('https://example.com/item/123.html')

soup = BeautifulSoup(r.text, 'lxml')

这似乎不起作用。 Cookie 未设置。感谢您的帮助。

【问题讨论】:

  • 您首先发送一个带有 cookie 的 POST 请求,然后发送一个不带 cookie 的 GET 请求。你到底想达到什么目的?
  • 我是新手,所以不要太认真地对待我的代码。默认网页为俄语,货币为卢布。我想将货币更改为美元,然后用 BS4 解析页面。

标签: python-3.x beautifulsoup python-requests


【解决方案1】:

由于您只想检索和解析网页的内容,因此这里不需要 POST 请求(请参阅this post)。只需使用:

s = requests.Session()
r = s.get('https://example.com/item/123.html', cookies=cookies)

【讨论】:

  • 感谢您的帮助。但是如何将这个带有 cookie 的请求传递给 BS4?我收到 AttributeError: 'NoneType' 对象没有属性 'text'。
  • 这意味着请求没有返回任何东西。您确定网页 URL 有效吗?
  • 我这边出了点问题。现在一切正常。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 2014-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多