Невозможно правильно отправить заявку, используя почтовые запросы с несколькими параметрами - PullRequest
2 голосов
/ 10 апреля 2020

Я пытаюсь отправить заявку после заполнения формы, доступной на веб-странице, используя python. Я пытался имитировать c процесс, который я вижу в chrome инструментах разработчика, но кажется, что я где-то ошибся, и именно поэтому при выполнении следующего скрипта я получаю эту ошибку:

{
"message":"415 Unsupported Media Type returned for /apply-app/rest/jobs/PIDFK026203F3VBQB79V77VIY-87592/submissions with message: ",
"key":"Exception_server_error",
"errorId":"d6b128bd-426d-4bee-8dbb-03e232829f5e"
}

Мне кажется, что мне нужно использовать значения token и version автоматически c, поскольку они различны в каждом приложении, но я не нахожу их в исходном коде и прочем.

Я выбрал No в качестве значения для всех раскрывающихся меню (если они есть) в пределах Additional Information.

Ссылка на страницу приложения

Ссылка на приложение, которое я использовал трижды.

Я пробовал с:

import requests

main_link = "https://karriere.hsbc.de/stellenangebote/stellenboerse/apply?jobId=PIDFK026203F3VBQB79V77VIY-87592&langCode=de_DE"
post_link = "https://emea3.recruitmentplatform.com/apply-app/rest/jobs/PIDFK026203F3VBQB79V77VIY-87592/submissions"

payload = {
    "candidateIdentity":{"firstName":"syed","lastName":"mushfiq","email":"mthmt80@gmail.com"},
    "answeredDocuments":[{"documentType":"answeredForm","formId":"hsbc_bewerbungsprozess_pers_nliche_daten",
    "answers":[
    {"questionId":"form_of_address","type":"options","value":["form_of_address_m"]},
    {"questionId":"academic_title","type":"simple","value":" Dr.","questionIds":[]},
    {"questionId":"first_name","type":"simple","value":"syed","questionIds":[]},
    {"questionId":"last_name","type":"simple","value":"mushfiq","questionIds":[]},
    {"questionId":"e-mail_address","type":"simple","value":"mthmt80@gmail.com","questionIds":[]},
    {"questionId":"phone__mobile_","type":"phone","countryCode":"+880","isoCountryCode":"BD","subscriberNumber":"1790128884"}]},
    {"documentType":"answeredForm","formId":"hsbc_bewerbungsprozess_standard_fragebogen","answers":[{"questionId":"custom_question_450","type":"options","value":["custom_question_450_ja"]},
    {"questionId":"custom_question_451","type":"options","value":["custom_question_451_nein"]},
    {"questionId":"custom_question_452","type":"options","value":["custom_question_452_unter_keine_der_zuvor_genannten"]},
    {"questionId":"custom_question_580","type":"options","value":["custom_question_580_nein_978"]},
    {"questionId":"custom_question_637","type":"options","value":["custom_question_637_nein"]},
    {"questionId":"custom_question_579","type":"options","value":["custom_question_579_nein"]},
    {"questionId":"custom_question_583","type":"options","value":["custom_question_583_hsbc_deutschland_karriereseite"]}]},

    #============The following three lines are supposed to help upload three files============

    {"documentType":"attachment","attachmentId":"cover_letter","token":"2d178469-cdb5-4d65-9f67-1e7637896953","filename": open("demo.pdf","rb")},
    {"documentType":"attachment","attachmentId":"attached_resume","token":"81a5a661-66bb-4918-a35c-ec260ffb7d02","filename": open("demo.pdf","rb")},
    {"documentType":"attachment","attachmentId":"otherattachment","token":"4c3f7500-b072-48d4-83cf-0af1399bc8ba","filename": open("demo.pdf","rb")}],

    #============The version's value should not be hardcoded=========================

    "version":"V2:3:14dfac80702d099625d0274121b0dba68ac0fd96:861836b7d86adae8cc1ce69198b69b8ca59e2ed5","lastModifiedDate":1562056029000,"answeredDataPrivacyConsents":[{"identifier":"urn:lms:ta:tlk:data-privacy-consent:mtu531:101","consentProvided":True},
    {"identifier":"urn:lms:ta:tlk:data-privacy-consent:mtu531:102","consentProvided":True}],
    "metaInformation":{"applicationFormUrl":"https://karriere.hsbc.de/stellenangebote/stellenboerse/apply?jobId=PIDFK026203F3VBQB79V77VIY-87592&langCode=de_DE","jobsToLink":[]}
}

def send_application(s,link):   
    res = s.post(link,data=payload)
    print(res.text)

if __name__ == '__main__':
    with requests.Session() as s:
        send_application(s,post_link)

Как правильно отправить заявку?

PS Я могу отправить заявку вручную несколько раз, используя одни и те же документы к одному и тому же адресу электронной почты.

Ответы [ 2 ]

4 голосов
/ 18 апреля 2020

Лучший способ go примерно в таком духе - открыть страницу в браузере и просмотреть вкладку сети в инструментах разработчика. Оттуда, заполнив форму, вы увидите, что каждый раз, когда вы прикрепляете документ, он отправляет запрос ajax и получает токен в ответе json. С помощью этих токенов вы можете создать окончательную полезную нагрузку, которая должна быть представлена ​​в формате json.

Вот пример кода, который работает:

import requests

headers = {
    'Host': 'emea3.recruitmentplatform.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate',
    'apply-config-key': 'AAACEwAA-55cd88d4-c9fd-41ce-95a4-f238402b898f',
    'Origin': 'https://karriere.hsbc.de',
    'DNT': '1',
    'Connection': 'close',
    'Referer': 'https://karriere.hsbc.de/',
    'Cookie': 'lumesse_language=de_DE'
}

main_link = "https://karriere.hsbc.de/stellenangebote/stellenboerse/apply?jobId=PIDFK026203F3VBQB79V77VIY-87592&langCode=de_DE"
post_link = "https://emea3.recruitmentplatform.com/apply-app/rest/jobs/PIDFK026203F3VBQB79V77VIY-87592/submissions"
ajax_link = "https://emea3.recruitmentplatform.com/apply-app/rest/jobs/PIDFK026203F3VBQB79V77VIY-87592/attachments"

def build_payload(cover_letter_token, attached_resume_token, otherattachment_token):
    return {
      "candidateIdentity": {
        "firstName": "Syed",
        "lastName": "Mushfiq",
        "email": "mthmt80@gmail.com"
      },
      "answeredDocuments": [
        {
          "documentType": "answeredForm",
          "formId": "hsbc_bewerbungsprozess_pers_nliche_daten",
          "answers": [
            {
              "questionId": "form_of_address",
              "type": "options",
              "value": [
                "form_of_address_m"
              ]
            },
            {
              "questionId": "academic_title",
              "type": "simple",
              "value": "prof",
              "questionIds": []
            },
            {
              "questionId": "first_name",
              "type": "simple",
              "value": "Syed",
              "questionIds": []
            },
            {
              "questionId": "last_name",
              "type": "simple",
              "value": "Mushfiq",
              "questionIds": []
            },
            {
              "questionId": "e-mail_address",
              "type": "simple",
              "value": "mthmt80@gmail.com",
              "questionIds": []
            },
            {
              "questionId": "phone__mobile_",
              "type": "phone",
              "countryCode": "+49",
              "isoCountryCode": "DE",
              "subscriberNumber": "30 33850062"
            }
          ]
        },
        {
          "documentType": "answeredForm",
          "formId": "hsbc_bewerbungsprozess_standard_fragebogen",
          "answers": [
            {
              "questionId": "custom_question_450",
              "type": "options",
              "value": [
                "custom_question_450_ja"
              ]
            },
            {
              "questionId": "custom_question_451",
              "type": "options",
              "value": [
                "custom_question_451_nein"
              ]
            },
            {
              "questionId": "custom_question_452",
              "type": "options",
              "value": [
                "custom_question_452_unter_keine_der_zuvor_genannten"
              ]
            },
            {
              "questionId": "custom_question_580",
              "type": "options",
              "value": [
                "custom_question_580_ja"
              ]
            },
            {
              "questionId": "custom_question_637",
              "type": "options",
              "value": [
                "custom_question_637_nein"
              ]
            },
            {
              "questionId": "custom_question_579",
              "type": "options",
              "value": [
                "custom_question_579_nein"
              ]
            },
            {
              "questionId": "custom_question_583",
              "type": "options",
              "value": [
                "custom_question_583_linkedin"
              ]
            }
          ]
        },
        {
          "documentType": "attachment",
          "attachmentId": "cover_letter",
          "token": cover_letter_token,
          "filename": "demo.pdf"
        },
        {
          "documentType": "attachment",
          "attachmentId": "attached_resume",
          "token": attached_resume_token,
          "filename": "demo.pdf"
        },
        {
          "documentType": "attachment",
          "attachmentId": "otherattachment",
          "token": otherattachment_token,
          "filename": "demo.pdf"
        }
      ],
      "version": "V2:3:14dfac80702d099625d0274121b0dba68ac0fd96:861836b7d86adae8cc1ce69198b69b8ca59e2ed5",
      "lastModifiedDate": "1562056029000",
      "answeredDataPrivacyConsents": [
        {
          "identifier": "urn:lms:ta:tlk:data-privacy-consent:mtu531:101",
          "consentProvided": "true"
        },
        {
          "identifier": "urn:lms:ta:tlk:data-privacy-consent:mtu531:102",
          "consentProvided": "true"
        }
      ],
      "metaInformation": {
        "applicationFormUrl": "https://karriere.hsbc.de/stellenangebote/stellenboerse/apply?jobId=PIDFK026203F3VBQB79V77VIY-87592&langCode=de_DE",
        "jobsToLink": []
      }
    }

def submit_attachment(s, link, f):
    d = open(f, 'rb').read()
    r = s.post(link, files={'file':('demo.pdf', d),'applicationProcessVersion':(None, 'V2:3:14dfac80702d099625d0274121b0dba68ac0fd96:861836b7d86adae8cc1ce69198b69b8ca59e2ed5')})
    r_data = r.json()
    return r_data.get('token')

def send_application(s,link,p):   
    res = s.post(link, json=p)
    return res

if __name__ == '__main__':
    attachment_list = ["cover_letter_token", "attached_resume_token", "otherattachment_token"]
    token_dict = {}

    with requests.Session() as s:
        s.headers.update(headers)

        for at in attachment_list:
            rt = submit_attachment(s, ajax_link, "demo.pdf")
            token_dict[at] = rt

        payload = build_payload(token_dict['cover_letter_token'], token_dict['attached_resume_token'], token_dict['otherattachment_token'])

        rd = send_application(s, post_link, payload)
        print(rd.text)
        print(rd.status_code)
0 голосов
/ 12 апреля 2020

В вашем коде под комментарием The following three lines are supposed to help upload three files вы указываете имя файла в конце JSON. Вместо того, чтобы просто указать имя файла, вы даете ему python объект файла, открытый в двоичном виде. Я думаю, вам нужно просто указать путь к файлу.

"filename": "\Users\username\Downloads\demo.pdf"

Я скажу, что я не очень знаком с модулем запросов python.

Надеюсь, это помогает.

...