python requests (form filling) - python-3.x

This is the link to a page
filling forms...
https://anotepad.com/notes/2yrwpi
where I have to enter the content in the text area (say)("hello world") and then press save, but all this is to be done with python request module (get, post etc)
and without the use of selenium and beautifulsoup module.
I tried something like:
url="https://anotepad.com/notes/2yrwpi"
txt = "Hello World"
#construct the POST request
form_data = {'btnSaveNote':'Save', 'notecontent' : txt}
post = requests.post(url,data=form_data)
But that doesn't seem to be working
Please help!

You need to login and post to the save url, you also need to pass the note number in the form data:
import requests
save = "https://anotepad.com/note/save"
txt = "Hello World"
login = "https://anotepad.com/create_account"
data = {"action": "login",
"email": "you#whatever.com",
"password": "xxxxxx",
"submit": ""}
# construct the POST request
with requests.session() as s: # Use a Session object.
s.post(login, data) # Login.
form_data = {"number": "2yrwpi",
"notetype": "PlainText",
"noteaccess": "2",
"notequickedit": "false",
"notetitle": "whatever",
"notecontent": txt}
r = s.post(save, data=form_data) # Save note.
r.json() will give you {"message":"Saved"} on success. Also if you want to see what notes you have, after logging in, run s.post("https://anotepad.com/note/list").text.

Related

python using requests and a webpage with a login issue

I'm trying to login to a website via python to print the info. So I don't have to keep logging into multiple accounts.
In the tutorial I followed, he just had a login and password, but this one has
Website Form Data
Does the _wp attributes change each login?
The code I use:
mffloginurl = ('https://myforexfunds.com/login-signup/')
mffsecureurl = ('https://myforexfunds.com/account-2')
payload = {
'log': '*****#gmail.com',
'pdw': '*****'
'''brandnestor_action':'login',
'_wpnonce': '9d1753c0b6',
'_wp_http_referer': '/login-signup/',
'_wpnonce': '9d1753c0b6',
'_wp_http_referer': '/login-signup/'''
}
r = requests.post(mffloginurl, data=payload)
print(r.text)
using the correct details of course, but it doesn't login.
I tried without the extra wordpress elements and also with them but it still just goes to the signin page.
python output
different site addresses, different login details
Yeah the nonce will change with every new visit to the page.
I would use request.session() so that it automatically stores session cookies and all that good stuff.
Do a session.GET('some_login_page.com')
Parse with the response content with BeautifulSoup to retrieve the nonce.
Then add that into the payload of your POST request when you login.
A very quick and dirty example:
import requests
from bs4 import BeautifulSoup as bs
email = 'test#email.com'
password = 'password1234'
url = 'https://myforexfunds.com/account-2/'
# Start a session
with requests.session() as session:
# Send a GET request to the login page
r = session.get(url)
# Check if the request was successful
if r.status_code != 200:
print("Get Request Failed")
# Parse the HTML content of the page
soup = bs(r.content, 'lxml')
# Extract the value of the nonce from the HTML
nonce = soup.find(id='woocommerce-login-nonce')['value']
# Set up the login form data
params ={
"username": email,
"password": password,
"woocommerce-login-nonce": nonce,
"_wp_http_referer": "/account-2/",
"login": "Log+in"
}
# Send a POST request with the login form data
r = session.post(url, params=params)
# Check if the request was successful
if r.status_code != 200:
print("Login Failed")

How to send a whatsapp message from python

I am trying to create a program which on certain conditions will send whatsapp message as notification. I want to perform this task without any third-party registration. Is there a way I can perform this using any python module or framework ?
Create a new file called "wasend.py" and write the following code on it:
import webbrowser
import pyautogui
from time import sleep
def send(text, phone):
webbrowser.open("whatsapp://send?text=" + text.replace('\n', '%0A') + "&phone=" + phone.replace('+', ''))
sleep(10)
pyautogui.click(x=1787, y=978)
sleep(0.2)
pyautogui.hotkey('enter')
sleep(1)
pyautogui.hotkey('alt', "f4")
Then, execute the following commands:
$ pip install pyautogui
$ pip install webbrowser
Create another file called "send.py". On it, write the following code:
import wasend
wasend.send("message", "phone")
I built this program. These are the params of the wasend.send() function:
wasend.send(message, number)
> message
The message in plain text. (Use * for bold, _ for italic, and plain Whatsapp formatting)
Write "\n" to make a line break.
> number
The phone number in the format: IIINNNNNNNNN (i = indicative, n = number, without the plus sign)
The program takes 11.5 seconds to execute (you can change the sleep to make it fast, but give some time to WhatsApp to load. If you already have WhatsApp loaded, change line 7 in wasend.py to sleep(1), so the program takes only 2.5 seconds to load.
You could do it in the following way, I hope it helps.
import requests
import json
PHONE_ID = "<whatsapp-phone-id>"
TOKEN = "<whatsapp-token>"
NUMBER = "<number>"
MESSAGE = "<message>"
URL = "https://graph.facebook.com/v13.0/"+PHONE_ID+"/messages"
headers = {
"Authorization": "Bearer "+TOKEN,
"Content-Type": "application/json"
}
data = {
"messaging_product": "whatsapp",
"to": NUMBER,
"type": "text",
"text": json.dumps({ "preview_url": False, "body": MESSAGE})
}
response = requests.post(URL, headers=headers, data=data)
response_json = response.json()
print(response_json)
You can find more details in the following source https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#text-object

Facebook messenger chatbot with Flask and pymessenger

I have created a messenger chatbot with flask, pymessenger and wit.ai.
I want to add facebook provided templates (like buttons, adding images and sound media)(https://developers.facebook.com/docs/messenger-platform/reference/template/button/)
There using some curl and json thing which I do not understand. Can some one help me, where should I put these snippet in my python code.
#app.route('/', methods=['POST'])
def webhook():
data = request.get_json()
log(data)
if data['object'] == 'page':
for entry in data['entry']:
for messaging_event in entry['messaging']:
sender_id = messaging_event['sender']['id']
recipient_id = messaging_event['recipient']['id']
if messaging_event.get('message'):
if 'text' in messaging_event['message']:
messaging_text = messaging_event['message']['text']
else:
messaging_text = 'no text'
response = None
entity, value = wit_response(messaging_text)
if entity == 'newstype':
response = "OK. I will send you {} news".format(str(value))
elif entity == 'cust_greet':
response = get_message()
elif entity == 'cust_bye':
response = "Bye! Have a Good Day!".format(str(value))
elif entity == 'cust_option':
response = "Option 1: Option 2:"
bot.send_text_message(sender_id, response)
return "ok", 200
def log(message):
print(message)
sys.stdout.flush()
HTTP requests use one of these two formats:
GET: All the request information is in the url
POST: Some information is sent via a JSON format to the url
What we see in the Facebook API is a POST request: the url is defined as
https://graph.facebook.com/v2.6/me/messages?access_token=<PAGE_ACCESS_TOKEN>
...and there is POST request information in the JSON section underneath
Curl is a program used to send HTTP requests from the terminal. If you install Curl, you can fill in the JSON/url information, run the command (which sends the POST request), and see the buttons pop up for the recipient. Just as you want your chatbot to do!
However, Curl is a tool, not a Python library!
To do this in Python, you can send the request through Python's built in libraries, or install a package which makes this easier (such as requests), look into "sending http requests via python".
Below is an example (adapted from this question):
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# the url we are sending the request to
url = "https://graph.facebook.com/v2.6/me/..."
# the POST request data
request_data = {
"recipient": {
"id": "<PSID>"
},
"message": {
"attachment": {
...
}
}
}
# create the request with the url and the data
post_request = Request(url, urlencode(request_data).encode())
# send it to Facebook! Response is the API response from Facebook
response = urlopen(post_request).read().decode()

Request module python

I'm having trouble using Python's request module.I'm trying to login to a webpage but it does not allow my connection.I don't really know if it might be a validation problem. Here is the code I'm using and the link of the page. It never shows me the page (The one I'm trying to access after I log in).
import requests
with requests.Session() as c:
username = "*******"
password = "******"
payload = {"userPri": username, "password": password}
url="https://declaraciones.sri.gob.ec/tuportalinternet/verificaEmail.jspa"
c.post("",data=payload)
page=c.get("another webpage")
print (page.content)`

Fill out online form

I'm trying to fill out the form located at https://idp.ncedcloud.org/idp/AuthnEngine#/authn with a username and password. I want to know if went through successfully or not. I tried it ith python2, but I couldn't get it to work.
#!/usr/bin/env python
import urllib
import urllib2
name = "username"
name2 = "password"
data = {
"description" : name,
"ember501": name2
}
encoded_data = urllib.urlencode(data)
content = urllib2.urlopen("https://idp.ncedcloud.org/idp/AuthnEngine#/authn",
encoded_data)
print(content)
error:
It prints the content of the same webpage, and I want it to print the new webpage content.
desired behavior:
python3 solution that goes to the next webpage, or why my code isn't working
Basic example of posting data to a webpage like this using requests library. I would suggest using session, so that your login info is saved for any following requests:
import requests
url = "http://example.com"
name = "username"
name2 = "password"
data = {
"description" : name,
"ember501": name2
}
s = requests.Session()
# If it supports basic auth you could just do
# s.auth(username, password) here before a request
req = s.post(url, data=data)
print(req.text)
Should then be able to do following requests with the s session object

Resources