【问题标题】:Posting CSRF Token with multiple tokens?使用多个令牌发布 CSRF 令牌?
【发布时间】:2018-06-05 09:51:12
【问题描述】:

我一直在尝试通过登录(使用 yelp)来抓取网站。为了更好地理解的第一个问题:我遵循了一些教程来获得这些想法,并注意到它们都使用 CSRF 令牌制作字典,但是,当我抓取 yelp 登录站点时,我发现了 6 个令牌。我知道我的字典中不能有重复的键,所以本教程使用字典来处理这种冗余/不正确的情况,因为我只会得到最后一个标记?

其次,如果有多个令牌,你使用哪个?或者你如何使用它们?我似乎无法登录,并阅读了 BeautifulSoup 和 Requests 的文档,并在昨晚搜索了 Stack。代码如下。 感谢您的任何解释。

s = requests.session()
login = s.get('https://www.yelp.com/login')

soup = BeautifulSoup(login.text, 'html.parser')
tokenList = soup.find_all(type = 'hidden', attrs={"name": "csrftok"})
c = login.cookies  #Just peeked into cookies to see if there is a token 
print(c)

keys = [x.attrs["name"] for x in tokenList]
values = [x.attrs["value"] for x in tokenList]
#If I print these two lists, I get 6 keys of the "csrftok" String, and 6 
#different keys.  

email = "my email"
password = "my password"
#I tried creating a dictionary with zip of all the tokens, etc. This 
#is an attempt just using the first key and value I find.
d = {'email': email, 'password': password, keys[0]: values[0]}
response = s.post('https://www.yelp.com/login', data = d)

print(response.url)

【问题讨论】:

    标签: python web-scraping beautifulsoup csrf


    【解决方案1】:

    你试过这样吗?我认为它应该引导你走向正确的方向:

    s = requests.session()
    login = s.get('https://www.yelp.com/login')
    
    soup = BeautifulSoup(login.text, 'lxml')
    token = soup.select(".csrftok")[0]['value']
    
    email = "my email"
    password = "my password"
    
    headers={
    'accept':'application/json, text/javascript, */*; q=0.01',
    'accept-encoding':'gzip, deflate, br',
    'content-type':'application/x-www-form-urlencoded; charset=UTF-8',
    'referer':'https://www.yelp.com/login',
    'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
    'x-distil-ajax':'fytrybseesxsvsresb',
    'x-requested-with':'XMLHttpRequest'
    }
    
    payload = {
    'csrftok':token,
    'email':email,
    'password':password,
    }
    
    response = s.post('https://www.yelp.com/login/newajax', data = payload, headers=headers)
    print(response.url)
    

    【讨论】:

    • 忘记添加headers。已经修好了。我没有办法检查它。不过,请告诉我。
    • 好的,我现在得到一个有效的状态响应,但是,如果打印 response.url,它应该在登录后返回新的 url,对吗?我不相信它正在登录,否则我应该能够搜索我的名字,例如在文本中并返回一个布尔值?另外,我假设 newajax 是您的位置,应该从我自己的代码中删除?
    • 当您打印response.textresponse.json() 因为响应应该是json 格式时,您看到了什么?我查不出来顺便说一句,我假设您设置了从chrome/firefox developer tools 派生的请求参数。如果你没有按照我推测的方式做,那么我上面使用的参数应该是正确的。
    • 好的,所以我意识到 newajax 是一个命令,而不是一个位置。我现在到达验证码文本。您对参数的假设也是正确的。我想我会暂时让它休息,直到验证码消失。谢谢!另外,是否有任何特殊原因必须在 xml 而不是 html 中解析它?
    • Html.parser 没问题。但是,我会给你一个链接来澄清我为什么选择 lxml。现在在移动设备上。
    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 2018-04-05
    • 2014-01-02
    • 2019-06-01
    • 2013-05-21
    • 2012-07-08
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多