簡體   English   中英

使用 Python 中的模塊請求通過 Facebook 登錄站點

[英]Login to a site through facebook with module requests in Python

我想通過 facebook 登錄到一個網站 (webnovel.com)。 這是我的代碼:

import requests
from bs4 import BeautifulSoup
import re

headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0'
}

with requests.session() as session:
    session.headers.update(headers)

    homepage=session.get('https://www.webnovel.com')
    loginFb=session.get('https://ptlogin.webnovel.com/login/facebook?appid=900&areaid=1&returnurl=https%3A%2F%2Fwww.webnovel.com%2FloginSuccess&auto=1&autotime=0&source=&ver=2&fromuid=0&target=iframe&option=&logintab=&popup=1&format=redirect', allow_redirects=False)
    loginFb2=session.get(loginFb.headers['Location'], allow_redirects=False)
    loginFb3=session.get(loginFb2.headers['Location'], allow_redirects=False)
    soup=BeautifulSoup(loginFb3.text,'html.parser')

    action_url = soup.find('form', id='login_form')['action']
    link=re.search(r'https.*',action_url).group()
    hexInLink=re.findall(r'%[0-9A-Z]{2,2}',link)
    for item in hexInLink:
        link=link.replace(item,bytearray.fromhex(item[1:]).decode())
    action_url=link

    inputs = soup.find('form', id='login_form').findAll('input', {'type': ['hidden', 'submit']})
    post_data = {input.get('name'): input.get('value')  for input in inputs}
    post_data['email'] = 'email'
    post_data['pass'] = 'pass'
    scripts = soup.findAll('script')
    scripts_string = '/n/'.join([script.text for script in scripts])
    datr_search = re.search(r'\["_js_datr","([^"]*)"', scripts_string, re.DOTALL)
    if datr_search:
        datr = datr_search.group(1)
        cookies = {'_js_datr' : datr}
    r=session.post(action_url, data=post_data, cookies=cookies, allow_redirects=True)
    print(r.history[0].url)

但是我在沒有登錄的情況下被重定向到同一個 facebook 頁面。顯然 POST 請求方法沒有被接受,但我不知道還有什么要改變或要添加什么信息。

感謝您的幫助

檢查第一頁上是否有_js_datr 我有同樣的問題,發現有時沒有datr

此外,您可以使用loginFb3.textr.text內容將所有頁面保存在單獨的文件中以進行調試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM