python requests 登录后跳转请求代码

python requests 登录后跳转请求代码

Python 的requests库中的登录主要用到的是 Post 请求

将两个 URL 分配给变量:‎

#这个是登录地址.
POST-LOGIN-URL = 'https://my.freecycle.org/login'

#这个是登录后跳转的地址.
REQUEST-URL = 'https://my.freecycle.org/home/posts'

Pythonic and self-explanatory. Let’s move on.

Now we want to set up a dict that contains our login information.

payload = {
    username: your_username,
    'pass’: ‘your_password'
}

The keys in the dict are the s of the input fields collected earlier. Eg:  and . The values associated with each are (you guessed it!) your username and password details. It’d be a good idea to at the very least, store your password in an environment variable and call it in for use in the script.nameusernamepass

Finally, we want to open our  . Yep! Requests will create its own session instance (useful for multiple requests to the same site):requestssession

with requests.Session() as session:
    post = session.post(POST-LOGIN-URL, data=payload)
    r = session.get(REQUEST-URL)
    print(r.text)   #or whatever else you want to do with the request data!
  • We’ll use a  statement to open the request Pythonically.with
  • Line 2 POSTS the data to the login URL we noted down earlier. It requires  to be specified, in which case we pass it the  dict we created. This is the part that enters our username and password!datapayload
  • Line 3 is our traditional requests call using  to the URL we want to scrape.session.get
  • Line 4 is where you’ll continue on with your requests work. To keep it simple I’ll leave it at a  statement that will print the entire page.print

Using Python Requests on a Page Behind a Login – PyBites

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据