I am doing a project and I want him to be invisible. Therefore, i used this website - http://pytoexe.com/ to create an window based exe file from my python script which means it will not use the windows console.
Unfortuently, since i am using phantomjs driver in my code, he opens a phantomjs console which interrupt me.
In order to slove this problem I need to add a line or script that prevent from the phantomjs console to appear ( changing something in my selenium files/ something like that would not work cause it probably problem in their files and i cannot doing anything with that) .
Someone know what to do?
this is my exe file
and This is my code:
from selenium import webdriver
import time
from PIL import Image
from constants import *
import operator
import os
#Email Constants
DEFAULT_CONTENT = 'example email stuff here'
HOST = 'smtp.gmail.com'
PORT = 587
EMAIL = 'freeadsandspam#gmail.com'
CUSTOMERS = []
SUBJECTS = ['new ad were found', 'ad were found by SMADS', 'best ad for you']
COMMASPACE = ', '
#Getting History
OUTPUT_FILE_PATH = 'C:\search_logger.txt'
COPY_OF_THE_HISTORY_PATH = 'C:\history'
NEW_OUTPUT_FILE_PATH = 'C:\last_search_logger.txt'
#PhantomJs And Ads Finding
PHANTOM_JS_PATH = 'C:\phantomjs-2.1.1-windows\\bin\phantomjs.exe'
OUTPUT_AD_PATH = 'ad.png'
DEFAULT_WINDOW_SIZE = (1024, 768)
AD_DATABASE = 'https://www.findads.com.au/'
KEYWORD_BUTTON_XPATH = '//*[#id="txtSearch"]'
SEARCH_BUTTON_XPATH = '/html/body/div[1]/div/form/button'
CONSTANT_TIME_SLEEPING = 3
AD_XPATH = '/html/body/div[1]/section/div/div[1]/div[4]/div[1]/div[1]/section[24]'
COMPARE_ELEMENT_XPATH = '//*[#id="fSearch"]'
CATAGORY_SORT_XPATH = '/html/body/div[1]/section/div/div[1]/div[5]/div/div[3]/form/div[1]/div[1]'
class PhantomJsDriver:
"""
A class that taking care on the ads finding
in the internet, doing it with PhantomJs -
background driver
"""
def __init__(self, ad_keyword, window_size=DEFAULT_WINDOW_SIZE, panthom_js_path=PHANTOM_JS_PATH, output_ad_path=OUTPUT_AD_PATH):
"""
this function init our object
in order to use the other functions
that the object offer.
Parameters
----------
phantom_js_path : str
path of the PhantomJs ( this essential because
we cannot get the PhantomJs file otherwise)
output_ad_path : str
where you want to save the ad that the system
had found and how you call the name of the ad
file ( eg: ad.png )
ad_keyword : str
the keyword that define what ad the system bring
( eg: dog will bring dog ad )
window_size : double int (int1,int2)
define the window size of the browser ( mainly for the
screenshot )
"""
self.phantom_js_path = panthom_js_path
self.output_ad_path = output_ad_path
self.ad_keyword = ad_keyword
self.window_size = window_size
self.list_of_images = []
self.dict = {}
def get_ad(self):
"""
this function save the ad by searching in the internet
( on specific website ) the keyword that the user chose
and copy it into the output_ad_path.
"""
for i in range(0, 5):
driver = webdriver.PhantomJS(self.phantom_js_path)
driver.set_window_size(self.window_size[0], self.window_size[1])
driver.get(AD_DATABASE)
keyword = driver.find_element_by_xpath(KEYWORD_BUTTON_XPATH)
keyword.send_keys(self.ad_keyword)
search_button = driver.find_element_by_xpath(SEARCH_BUTTON_XPATH)
search_button.click()
driver.save_screenshot("ad" + str(i) + ".png")
element = driver.find_element_by_xpath(AD_XPATH) # find part of the page you want image of
self.crop_image(i, element)
def crop_image(self, i, element):
"""
this function crop the screenshot of the ads website from
the previous function into one single ad.
"""
im = Image.open("ad" + str(i) + ".png") # uses PIL library to open image in memory
location = element.location
size = element.size
left = location['x']
top = location['y']
right = location['x'] + size['width'] + 50
bottom = location['y'] + size['height']
weight, height = im.size
print height
im = im.crop((left, top, right, bottom)) # defines crop points
im.save('test' + str(i) + '.png') # saves new cropped image
self.list_of_images.append('test' + str(i) + '.png')
self.dict['test' + str(i) + '.png'] = 0
def choose_the_best_ad(self):
for img1 in self.list_of_images:
for img2 in self.list_of_images:
im1 = Image.open(img1)
im2 = Image.open(img2)
if list(im1.getdata()) == list(im2.getdata()):
self.dict[img1] += 1
self.dict[img2] += 1
print self.dict
BestImage = max(self.dict.iteritems(), key=operator.itemgetter(1))[0]
print BestImage
if os.path.exists("TheImage.png"):
os.remove("TheImage.png")
os.rename(BestImage, "TheImage.png")
driver = PhantomJsDriver("dog")
driver.get_ad()
driver.choose_the_best_ad()
Related
I'm trying to make a music app using python for my 12th grade project but I'm getting an error which I have no idea how to fix. What I'm indenting to do is to make fully functional app-like python program with GUI and is able to play both online and offline music.
Initially I started with just a program in which we can search and find the first result which comes in Youtube and just play it, pause it and stop it. Which I later improved so that we can play upto the first 10 results in Youtube.I actually got the idea for the searching and finding part from stack overflow itself (which was very helpful btw.) and developed the rest of the code from it. We also can play/pause/stop the music too. But I wanted it to look even more good so...I added a GUI using tkinter which was pretty hard at first but soon it was easy enough. What I can do now is Type the music name in the Tkinter window and Search button (added the Search button so it will run the 'link-finding-and-playing-program' when I press it).
The libraries I use now are:
requests.
pafy
python-vlc
tkinter
CODE OF THE PROGRAM:
from tkinter import *
import re,requests, urllib.parse, urllib.request
import vlc
import pafy
root = Tk()
root.geometry('475x225'); root.title('PyMu6')
Entry = Entry(root, width=26,font=('Circular',13))
Entry.place(x=127,y=17)
def search():
music_name = Entry.get()
print(music_name)
if type(music_name)==str:
query_string = urllib.parse.urlencode({"search_query": music_name})
formatUrl = urllib.request.urlopen("https://www.youtube.com/results?" + query_string)
search_results = re.findall(r"watch\?v=(\S{11})", formatUrl.read().decode())
clip = requests.get("https://www.youtube.com/watch?v=" + "{}".format(search_results[0]))
clip1 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[0])
clip2 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[1])
clip3 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[2])
clip4 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[3])
clip5= "https://www.youtube.com/watch?v=" + "{}".format(search_results[4])
clip6 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[5])
clip7 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[6])
clip8 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[7])
clip9 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[8])
clip10 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[9])
title1 = pafy.new(clip1)
title2 = pafy.new(clip2)
title3 = pafy.new(clip3)
title4 = pafy.new(clip4)
title5 = pafy.new(clip5)
title6 = pafy.new(clip6)
title7 = pafy.new(clip7)
title8 = pafy.new(clip8)
title9 = pafy.new(clip9)
title10 = pafy.new(clip10)
video1 = title1.title
video2 = title2.title
video3 = title3.title
video4 = title4.title
video5 = title5.title
video6 = title6.title
video7 = title7.title
video8 = title8.title
video9 = title9.title
video10 = title10.title
Label(root,text=video1,fg='blue').place(x=60,y=70)
print()
print('1)', video1)
print('2)', video2)
print('3)', video3)
print('4)', video4)
print('5)', video5)
print('6)', video6)
print('7)', video7)
print('8)', video8)
print('9)', video9)
print('10)', video10)
print()
e = input('Enter Song: ')
if e == '1':
print(clip1)
url = clip1
if e == '2':
print(clip2)
url = clip2
if e == '3':
print(clip2)
url = clip3
if e == '4':
print(clip4)
url = clip4
if e == '5':
print(clip5)
url = clip5
if e == '6':
print(clip6)
url = clip6
if e == '7':
print(clip7)
url = clip7
if e == '8':
print(clip8)
url = clip8
if e == '9':
print(clip9)
url = clip9
if e == '10':
print(clip10)
url = clip10
video = pafy.new(url)
best = video.getbest()
media = vlc.MediaPlayer(best.url)
titl = video.title
print(titl)
media.play()
def play():
media.play()
def pause():
media.pause()
def stop():
media.stop()
Search_button = Button(root, text = 'Search', width = 10, font = ('Circular.', 10),bg='#1DB954',command=MusicPlayer.search)
Play = Button(root, text = 'Play', width = 10,font = ('Circular.', 10),bg='#1DB954',command=play)
Pause = Button(root,text = 'Pause', width = 10, font = ('Circular.', 10),bg='#1DB954',command=pause)
Stop = Button(root,text = 'Stop', width = 10, font = ('Circular.',10),bg='#1DB954',command=stop)
Search_button.place(x=380,y=15);Play.place(x=120,y=170);Pause.place(x=220,y=170);Stop.place(x=320,y=170)
root.mainloop()
This code works pretty well enough till the place where pausing/playing/stopping buttons.
Whenever I Try to press those button I get a ValueError: name 'media' is not defined.
this is the link of the image of the error I get.The Problem I think is because I'm trying to use something which is not under its indent(media).
This is the player when it is working
I also tried other ways of returning this media attribute but they don't seem to work for me. So, It would be good if someone could help me with this error and fix it.Also,I'm welcome to any suggestions you have for the program.
Thanks
Sreeram
In the function, make media global variable. However using global is bad. You can go with OOP approach where you can access the instance variable anywhere inside the function provided it is defined
global media
media = vlc.MediaPlayer(best.url)
I don't know that will work or not but try to pass the media value in the def
like:
def play(media):
media.play()
You can create media outside search() and use media.set_mrl() inside search() instead:
media = vlc.MediaPlayer()
def search():
...
best = video.getbest()
media.set_mrl(best.url)
...
I am currently trying to take a screenshot of a specific web element using Selenium and Pillow on Python 2.7. The code I have seems to be able to take the screenshot and then crop the image but it is actually not cropping at the exact location of the element. After researching I found that this could be happening due to the dpi used by the Mac Book Pro retina display but I havenĀ“t found a workaround for this.
What could be the best way to handle this "issue" with the retina display and PIL?
This is the code I am using:
try:
#Wait until finishing loading
waitElement = WebDriverWait(driver,60).until(
EC.presence_of_element_located((By.XPATH, "//*[#id='someElement']/span/input[2]"))
)
try:
#Go to trends report
driver.get("https://somewebsite.com/trends")
waitElement = WebDriverWait(driver,60).until(
EC.presence_of_element_located((By.ID, "Totals"))
)
try:
summary = driver.find_element_by_id("Totals")
driver.save_screenshot("sc.png")
location = summary.location
size = summary.size
x = location['x']
y = location['y']
w = size['width']
h = size['height']
width = x + w
height = y + h
im = Image.open('sc.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('summary.png')
except NoSuchElementException:
print("Something")
except NoSuchElementException:
print("Something")
finally:
driver.close()
I was facing this (broken screenshot issue in case of ratina display on mac) & solved it using
Snippet I used for this
//basically , here I am using 'devicePixelRatio' to calculate proper width/height
WebElement ele = findElement(By.xpath(webElementXpath));
Point point = ele.getLocation();
int devicePixelRatio = Integer.parseInt(returnExecuteJavaScript("return window.devicePixelRatio"));
int eleWidth = ele.getSize().getWidth() * devicePixelRatio;
int eleHeight = ele.getSize().getHeight() * devicePixelRatio;
// ....... for cropping stuff , you can use your own code
I only see this description in this link, it hasn't a very detailed explanation, so I'd like to know where can I find a more detailed explanation.The official web document says "Length of the history", what "Length of the history" is?
My code:
import os
import time
import cv2
def main():
img_src_dirpath = r'C:/Users/Shinelon/Desktop/SRC/'
dir = r'D:/deal_pics/' + time.strftime('%Y-%m-%d') + '/'
if not os.path.exists(dir):
os.makedirs(dir)
img_dst_dirpath = dir
history = 60
varThreshold = 16
detectShadows = True
mog2 = cv2.createBackgroundSubtractorMOG2( history, varThreshold, detectShadows )
for f in os.listdir( img_src_dirpath ):
if f.endswith( '.jpg' ):
img = cv2.imread( img_src_dirpath + f )
mog2.apply( img )
bg = mog2.getBackgroundImage()
cv2.imwrite( img_dst_dirpath + f, bg )
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
As #usr2564301 said getHistory gives you good explanation in human language
Returns the number of last frames that affect the background model.
If you need a mathematical explanation of what it is - I would recommend you to read An improved adaptive background mixture model for real-time tracking with shadow detection paper which this algorithm is based on.
As you can see from sources (1, 2) history is used to calculate learningRate which is essentially alpha in that paper
I'm very new to python and I'm trying to print the url of an open websitein Chrome. Here is what I could gather from this page and googeling a bit:
import win32gui, win32con
def getWindowText(hwnd):
buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)
buf = win32gui.PyMakeBuffer(buf_size)
win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf)
return str(buf)
hwnd = win32gui.FindWindow(None, "Chrome_WidgetWin_1" )
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
print(getWindowText(hwnd))
I get this as a result:
<memory at 0x00CA37A0>
I don't really know what goes wrong, whether he gets into the window and the way I try to print it is wrong or whether he just doesn't get into the window at all.
Thanks for the help
Only through win32 can only get the information of the top-level application. If you want to get the information of each component located in the application, you can use UI Automation.
Python has a wrapper package Python-UIAutomation-for-Windows, and then you can get the browser's address bar url through the following code:
import uiautomation as auto
def get_browser_tab_url(browser: str):
"""
Get browser tab url, browser must already open
:param browser: Support 'Edge' 'Google Chrome' and other Chromium engine browsers
:return: Current tab url
"""
if browser.lower() == 'edge':
addr_bar = auto.EditControl(AutomationId='addressEditBox')
else:
win = auto.PaneControl(Depth=1, ClassName='Chrome_WidgetWin_1', SubName=browser)
temp = win.PaneControl(Depth=1, Name=browser).GetChildren()[1].GetChildren()[0]
for bar in temp.GetChildren():
last = bar.GetLastChildControl()
if last and last.Name != '':
break
addr_bar = bar.GroupControl(Depth=1, Name='').EditControl()
url = addr_bar.GetValuePattern().Value
return url
print(get_browser_tab_url('Edge'))
print(get_browser_tab_url('Google Chrome'))
print(get_browser_tab_url('Cent Browser'))
This should work:
import uiautomation as auto
control = auto.GetFocusedControl()
controlList = []
while control:
controlList.insert(0, control)
control = control.GetParentControl()
control = controlList[0 if len(controlList) == 1 else 1]
address_control = auto.FindControl(control, lambda c, d:
isinstance(c, auto.EditControl))
print('Current URL:')
print(address_control.GetValuePattern().Value)
Currently I'm using rsvg to load the svg (from a string, not from a file) and drawing to cairo. Anyone know a better way? I use PIL elsewhere in my application, but I don't know of a way to do this with PIL.
Here's what I currently have:
import cairo
import rsvg
def convert(data, ofile, maxwidth=0, maxheight=0):
svg = rsvg.Handle(data=data)
x = width = svg.props.width
y = height = svg.props.height
print "actual dims are " + str((width, height))
print "converting to " + str((maxwidth, maxheight))
yscale = xscale = 1
if (maxheight != 0 and width > maxwidth) or (maxheight != 0 and height > maxheight):
x = maxwidth
y = float(maxwidth)/float(width) * height
print "first resize: " + str((x, y))
if y > maxheight:
y = maxheight
x = float(maxheight)/float(height) * width
print "second resize: " + str((x, y))
xscale = float(x)/svg.props.width
yscale = float(y)/svg.props.height
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, x, y)
context = cairo.Context(surface)
context.scale(xscale, yscale)
svg.render_cairo(context)
surface.write_to_png(ofile)
How about imagemagic? - http://www.imagemagick.org/script/magick-vector-graphics.php It can read/write from/to stdin/stdout so You can integrate it with your app even if You don't want to use files
I have inkscape installed so I am just farming out the process to the inkscape command with inkscape -f file.svg -e file.png
Using this code:
import subprocess
inkscape_dir=r"C:\Program Files (x86)\Inkscape"
assert os.path.isdir(inkscape_dir)
os.chdir(inkscape_dir)
subprocess.Popen(['inkscape.exe',"-f",fname,"-e",fname_png])
I am on windows 7, and got the Windows 5 Error [Access Denied] (or something like that) until I switched to the inkscape directory
You can also use PhantomJS for this (see http://phantomjs.org/screen-capture.html)
From a shell:
phantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png
Or from python using selenium:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.set_window_size(1024, 768)
driver.get('http://ariya.github.com/svg/tiger.svg')
driver.save_screenshot('tiger.png')