I use this .py to send message automatically on whatsapp
The message 'INSTRUCTOR' contains Japanese, and the final Japanese message is garbled. Can you please help me to solve the messy code problem here?
the csv file:
enter image description here
the garbled message:
enter image description here
import pyautogui as pg
import webbrowser as web
import time
import pandas as pd
#Ensure that the .csv is in the correct format, otherwise the encoding format may be incorrect!
data = pd.read_csv('/Users/wen9953/Desktop/REV/Auto_Whatsapp/Customer04.csv', encoding='utf-8-sig')
data_dict = data.to_dict('list')
leads = data_dict['phone'] #Enter the corresponding column name in single quotes, and make sure the column name is correct
instructors = data_dict['INSTRUCTOR']
name = data_dict['NAME']
combo = zip(leads, instructors, name)
first = True
for leads, instructors, name in combo:
time.sleep(4)
web.open("https://web.whatsapp.com/send?phone=" + leads + "&text=" + "Hello " + name + "! I'm Chevon, a membership consultant from Revolution and I noticed that you recently attended " + instructors + "'s class! How was it? I would love to hear any feedback that you may have for us! :)")
if first:
time.sleep(6)
first = False
width, height = pg.size()
pg.click(width / 2, height / 2)
time.sleep(8)
pg.press('enter')
time.sleep(8)
pg.hotkey('ctrl', 'w')
Related
I think I've got to a point where I need help from professionals. I would like to build a scraper for a browser game that gives an alarm to a bot (Telegram or Discord). The connection of the bot is not the problem at first, it is more about getting the right result.
My script runs in a while-loop (it also runs without) and is supposed to look for links in an -tag. These links contain an ID. This is always incremented +1 when a new player signs up to the game and that's exactly what I need.
Since I need to compare the information, I figured I need to save it in a .csv file. And there lies the problem the output looks like this in the .csv:
index.php?section=impressum
I have two problems:
I want to limit the output to the first 5 results in the file
Only have in the file if something changes or the corresponding change.
1. + 2.
This ist my code so far:
import requests
import time
import csv
from datetime import datetime
from bs4 import BeautifulSoup
def writeCSV(data):
csv_file = open('ags_scrape.csv', 'w')
csv_writer = csv.writer(csv_file)
csv_writer.writerow([data])
csv_file.close()
sleepTimer = 3
# Adresse der Webseite
url = "https://www.ag-spiel.de/"
allAGs = []
firstRun = True
while True:
response = requests.get(url + "index.php?section=live")
# BeautifulSoup HTML-Dokument aus dem Quelltext parsen
html = BeautifulSoup(response.text, 'html.parser')
# url aus dem <a href> parsen
newDetected = False
newAGs = []
possible_links = html.find_all('a')
for link in possible_links:
if link.has_attr('href'):
inhalt = str(link.attrs['href'])
if "aktie=" in inhalt:
if firstRun is True:
allAGs.append(inhalt)
else:
if str(inhalt) not in allAGs:
newDetected = True
print("ATTENTION!!! New AG! Url is: " + inhalt)
allAGs.append(inhalt)
# in Datei schreiben
writeCSV(inhalt)
else:
# print ("Debug output "+ inhalt + " already in AGlist")
continue
if firstRun is True:
print("Frist run successfull, current ags: " + str(len(allAGs)))
for AGurl in allAGs:
print(AGurl)
else:
if newDetected is False:
print(str(datetime.now().strftime("%H:%M:%S")) + ": Nothing changed")
writeCSV(inhalt)
else:
print("Something Changed, current ags: " + str(len(allAGs)))
for AGurl in allAGs:
print(AGurl)
firstRun = False
time.sleep(sleepTimer)
ยดยดยดยด
Writing a game and no matter what I try it keeps giving me a syntax error for the 'as'.
I have tried looking through StackOverflow / changing my code to find a workaround but I have been unable to fix it so far
winner = input("Winner test username")
winnerscore = input("Test score")
open("leaderboardtest.txt","a") as leaderboard
leaderboard.write = "/n" , winner , " : " , winnerscore
(winner and winnerscore variables would have been made earlier just wrote it here during testing)
Invalid syntax highlight on the 'as'.
(I know this is a comparatively simple problem to other things on StackOverflow but I would appreciate any support.)
Looks like you have used incorrect syntax for writing text into file.
f = open("leaderboardtest.txt","a") # open file for append operation
f.write('\n' + winner + ' : ' + winnerscore) # write data whatever you want
f.close() # close file
There you go.
winner = input("Winner test username")
winnerscore = input("Test score")
with open("leaderboardtest.txt","a") as leaderboard:
string_to_write = "\n" + winner + " : " + winnerscore
leaderboard.write(string_to_write)
I'm trying to write a program that will go to a website and download all of the songs they have posted. Right now I'm having trouble creating new file names for each of the songs I download. I initially get all of the file names and the locations of the songs (html). However, when I try to create new files for the songs to be put in, I get an error saying:
IOError: [Errno 22] invalid mode ('w') or filename
I have tried using different modes like "w+", "a", and, "a+" to see if these would solve the issue but so far I keep getting the error message. I have also tried "% name"-ing the string but that has not worked either. My code is following, any help would be appreciated.
import urllib
import urllib2
def earmilk():
SongList = []
SongStrings = []
SongNames = []
earmilk = urllib.urlopen("http://www.earmilk.com/category/pop")
reader = earmilk.read()
#gets the position of the playlist
PlaylistPos = reader.find("var newPlaylistTracks = ")
#finds the number of songs in the playlist
NumberSongs = reader[reader.find("var newPlaylistIds = " ): PlaylistPos].count(",") + 1
initPos = PlaylistPos
#goes though the playlist and records the html address and name of the song
for song in range(0, NumberSongs):
songPos = reader[initPos:].find("http:") + initPos
namePos = reader[songPos:].find("name") + songPos
namePos += reader[namePos:].find(">")
nameEndPos = reader[namePos:].find("<") + namePos
SongStrings.append(reader[songPos: reader[songPos:].find('"') + songPos])
SongNames.append(reader[namePos + 1: nameEndPos])
#initPos += len(SongStrings[song])
initPos = nameEndPos
for correction in range(0, NumberSongs):
SongStrings[correction] = SongStrings[correction].replace('\\/', "/")
#downloading songs
#for download in range(0, NumberSongs):
#print reader.find("So F*")
#x= SongNames[0]
songDL = open(SongNames[0].formant(name), "w+")
songDL.write(urllib.urlretrieve(SongStrings[0], SongNames[0] + ".mp3"))
songDL.close()
print SongStrings
for name in range(0, NumberSongs):
print SongNames[name] + "\n"
earmilk.close()
You need to use filename = '%s' % (SongNames[0],) to construct the name but you also need to make sure that your file name is a valid one - I don't know of any songs called *.* but I wouldn't like to chance it so something like:
filename = ''.join([a.isalnum() and a or '_' for a in SongNames[0]])
I'm trying to make my code write to cells A1, A2, A3 and A4 in Excel. However, when I use it, I get this error message
Invalid Cell coordinates (A)
'A' stays constant but 'i' changes with each repetition. How would I fix the problem on line 27? I want to make Python accept "A" as a column reference.
This was line 27:
ws.cell('A',i).value = "The price of", symbolslist[i], " is ", price"
and my entire Python script:
from openpyxl import Workbook
import urllib
import re
from openpyxl.cell import get_column_letter
wb = Workbook()
dest_filename = r'empty_book.xlsx'
ws = wb.create_sheet()
ws.title = 'Stocks'
symbolslist = ["aapl","spy","goog","nflx"]
i=0
while i<len(symbolslist):
#counts each object as 1 in the list
url = "http://finance.yahoo.com/q?s="+symbolslist[i]+"&q1=1"
htmlfile = urllib.urlopen(url)
htmltext = htmlfile.read()
regex = '<span id="yfs_l84_'+symbolslist[i]+'">(.+?)</span>'
pattern = re.compile(regex)
price = re.findall(pattern,htmltext)
print "The price of", symbolslist[i], " is ", price
ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price
i+=1
wb.save(filename = dest_filename)
I am also using this as a reference, from openpyxl.
EDIT
Your i=0 on the first pass but there is no zero column. Also, I think the cell is looking for row index which is a number not a character 'A'.
ws.cell(1,i+1).value = "The price of" + symbolslist[i] + " is " + price
It is the use of ws.cell().value that is not correct. I had the error saying 'int' object has no attribute 'replace', but after I changed the line to the following, the error dispappeared:
ws.cell(row=1,column=i+1).value = "The price of" + str(symbolslist[i]) + " is " + str(price)
By the way, I am using Python 2.7 and the latest version of openpyxl
I have searched and searched but I have only found solutions involving php and not python/django. My goal is to make a website (backend coded in python) that will allow a user to input a string. The backend script would then be run and output a dictionary with some info. What I want is to use the info from the dictionary to sort of draw it onto an image I have on the server and give the new image to the user. How can I do this offline for now? What libraries can I use? Any suggestions on the route I should head on would be lovely.
I am still a novice so please forgive me if my code needs work. So far I have no errors with what I have but like I said I have no clue where to go next to achieve my goal. Any tips would be greatly appreciated.
This is sort of what I want the end goal to be http://combatarmshq.com/dynamic-signatures.html
This is what I have so far (I used beautiful soup as a parser from here. If this is too excessive or if I did it in a not so good way please let me know if there is a better alternative. Thanks):
The url where I'm getting the numbers I want (These are dynamic) is this: http://combatarms.nexon.net/ClansRankings/PlayerProfile.aspx?user=
The name of the player will go after user so an example is http://combatarms.nexon.net/ClansRankings/PlayerProfile.aspx?user=-aonbyte
This is the code with the basic functions to scrape the website:
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
def get_avatar(player_name):
'''Return the players avatar as a binary string.'''
player_name = str(player_name)
url = 'http://combat.nexon.net/Avatar/MyAvatar.srf?'
url += 'GameName=CombatArms&CharacterID=' + player_name
sock = urlopen(url)
data = sock.read()
sock.close()
return data
def save_avatar(data, file_name):
'''Saves the avatar data from get_avatar() in png format.'''
local_file = open(file_name + '.png', 'w' + 'b')
local_file.write(data)
local_file.close()
def get_basic_info(player_name):
'''Returns basic player statistics as a dictionary'''
url = 'http://combatarms.nexon.net/ClansRankings'
url += '/PlayerProfile.aspx?user=' + player_name
sock = urlopen(url)
html_raw = sock.read()
sock.close()
html_original_parse = BeautifulSoup(''.join(html_raw))
player_info = html_original_parse.find('div', 'info').find('ul')
basic_info_list = range(6)
for i in basic_info_list:
basic_info_list[i] = str(player_info('li', limit = 7)[i+1].contents[1])
basic_info = dict(date = basic_info_list[0], rank = basic_info_list[1], kdr = basic_info_list[2], exp = basic_info_list[3], gp_earned = basic_info_list[4], gp_current = basic_info_list[5])
return basic_info
And here is the code that tests out those functions:
from grabber import get_avatar, save_avatar, get_basic_info
player = raw_input('Player name: ')
print 'Downloading avatar...'
avatar_data = get_avatar(player)
file_name = raw_input('Save as? ')
print 'Saving avatar as ' + file_name + '.png...'
save_avatar(avatar_data, file_name)
print 'Retrieving ' + player + '\'s basic character info...'
player_info = get_basic_info(player)
print ''
print ''
print 'Info for character named ' + player + ':'
print 'Character creation date: ' + player_info['date']
print 'Rank: ' + player_info['rank']
print 'Experience: ' + player_info['exp']
print 'KDR: ' + player_info['kdr']
print 'Current GP: ' + player_info['gp_current']
print ''
raw_input('Press enter to close...')
If I understand you correctly, you want to get an image from one place, get some textual information from another place, draw text on top of the image, and then return the marked-up image. Do I have that right?
If so, get PIL, the Python Image Library. Both PIL and BeatifulSoup are capable of reading directly from an opened URL, so you can forget that socket nonsense. Get the player name from the HTTP request, open the image, use BeautifulSoup to get the data, use PIL's text functions to write on the image, save the image back into the HTTP response, and you're done.