使用python3和请求登录推特 [英] logging into a twitter using python3 and requests

查看:68
本文介绍了使用python3和请求登录推特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在处理的项目,要求是使用用户名和密码登录网站.我必须用 python 完成,然后才能访问网站的一部分,只有登录的人才能访问.我尝试了一些编码变体来做到这一点,但未能成功登录然而.这是我的编码:

I have a project that I am working on, and the requirements are to login to a website using a username and password. I have to do it in python, and then be able to access a part of the site only accessible to people who are logged in. I have tried a few variations of coding to do this, and haven't been able to successfully log in yet. Here is my coding:

登录功能:

定义 session2(url):

def session2(url):

#r = requests.get(url)
#ckies = []

#print("here are the cookies for twitter:\n")
#for cky in r.cookies:
#    print(cky.name, cky.value)
#    ckies.append(cky)

s = requests.Session()

session = s.get(url, verify=False)
print("\nheaders from site\n")
print(session.headers)

tree = html.fromstring(session.text)
# extract the auth token needed to login along with username and password
auth_token = list(set(tree.xpath("//input[@name='authenticity_token']/@value")))[0]
uname = "username"
pword = "password"
username = 'session[username_or_email]'
password = 'session[password]'
# payload = {name of username variable : string you want, name of password variable:
# string you want, name of auth token: string gotten from session
payload = dict(username = uname, password = pword , authenticity_token = auth_token)
header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'}
#do post request
# might have to change headers to be a header for chrome
response = s.post(
    url,
    data = payload,
    #headers = dict(referer = url)
    headers = header
)
print("\nheaders post\n")
print(response.request.headers)
session = s.get("http://www.twitter.com/username/followers", verify=False)
print("\nheaders get\n")
print(session.headers)
print("\nhtml doc\n")
print(session.text)
return session

调用它的代码:

url = "http://www.twitter.com/login"
sessions = session2(url)

网站上的用户名在您检查时如下所示:

the username on the site looks like this when you inspect it:

<input class="js-username-field email-input js-initial-focus" type="text" name="session[username_or_email]" autocomplete="on" value="" placeholder="Phone, email or username">

密码部分/令牌部分如下所示:

and the password section/token section look like this:

<input class="js-password-field" type="password" name="session[password]" placeholder="Password">

<input type="hidden" value="ef25cb09a8c7fe16c54e3df099e206e605b1170a" name="authenticity_token">

我知道身份验证令牌发生了变化,这就是我从函数中获取它的原因.当我尝试运行它时,它只会转到主页而不是我需要的页面.

I know the auth token changes, which is why i have it get it from the function. When I try to run this, it just goes to the main page rather than the page i need.

我认为的一个问题是,当我打印出我在帖子中发送的标题时,它说:

One problem I think is that when I print out the header that I send in the post, it says:

{'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Accept': '/', 'User-Agent': 'python-请求/2.9.1'}

{'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Accept': '/', 'User-Agent': 'python-requests/2.9.1'}

我以为我更改为 chrome 的标题,但它似乎没有坚持.

which I thought I changed to chrome's header, but it doesn't seem to stick.

另外,我知道如果我使用 Oauth 有一种方法,但我不允许使用它,我必须基于能够像使用浏览器一样登录来这样做.

Also, I know there is a way if I use Oauth, but I'm not allowed to use that, i have to do it based on being able to login like I'm using a browser.

你能告诉我我所做的是否有任何问题,以及如何解决它的任何提示吗?我已经尝试过使用请求和登录来解决其他堆栈溢出问题,但这些都不起作用.

Can you tell me if there is anything wrong with what I've done, as well as any hints on how to fix it? I've tried other stack overflow problems using requests and logging in, but those didn't work either.

好的,我做了一个 response.request.headers,它出现了正确的标题,我认为,所以我认为这不是问题

ok, i did a response.request.headers, and it came out with the right header, i think, so i don't think that is the problem

打印的标题:

 {'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36', 'Cookie': '_twitter_sess=some huge amount of number/letters; guest_id=v1%3A147509653977967101', 'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate'}

推荐答案

这将使您登录:

import requests
from bs4 import BeautifulSoup

username = "uname"
password = "pass"
# login url
post = "https://twitter.com/sessions"
url = "https://twitter.com"

data = {"session[username_or_email]": username,
        "session[password]": password,
        "scribe_log": "",
        "redirect_after_login": "/",
        "remember_me": "1"}


with requests.Session() as s:
    r = s.get(url)
    # get auth token
    soup = BeautifulSoup(r.content, "lxml")
    AUTH_TOKEN = soup.select_one("input[name=authenticity_token]")["value"]
    # update data, post and you are logged in.
    data["authenticity_token"] = AUTH_TOKEN
    r = s.post(post, data=data)
    print(r.content)

您可以查看我们是否使用自己的帐户运行它,我们会从我的个人资料中获取我的名字:

You can see if we run it using my own account, we get my name from my profile:

In [30]: post = "https://twitter.com/sessions"

In [31]: url = "https://twitter.com"

In [32]: data = {"session[username_or_email]": username,
   ....:         "session[password]": password,
   ....:         "scribe_log": "",
   ....:         "redirect_after_login": "/",
   ....:         "remember_me": "1"}

In [33]: with requests.Session() as s:
   ....:         r = s.get(url)
   ....:         soup = BeautifulSoup(r.content, "lxml")
   ....:         AUTH_TOKEN = soup.select_one("input[name=authenticity_token]")["value"]
   ....:         data["authenticity_token"] = AUTH_TOKEN
   ....:         r = s.post(post, data=data)
   ....:         soup = BeautifulSoup(r.content, "lxml")
   ....:         print(soup.select_one("b.fullname"))
   ....:     

<b class="fullname">Padraic Cunningham</b>

请注意,每次登录时,您都会收到我们注意到您的帐户最近登录... 电子邮件.

Just be aware each time you login, you will the We noticed a recent login for your account ... email.

这篇关于使用python3和请求登录推特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆