I want to upload my javascript and html code to qwebengine so that it will read the code and load it in the browser. Is this possible? I think there is some way to do this as I have been reading about it on the internet but I'm unsure of how to do so. My code for the browser is:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import *
class MyWebBrowser(QMainWindow):
def __init__(self,):
super(MyWebBrowser, self).__init__()
self.window=QWidget()
self.window.setWindowTitle("Brave")
self.layout=QVBoxLayout()
self.horizontal = QHBoxLayout()
self.url_bar = QTextEdit()
self.url_bar.setMaximumHeight(30)
self.go_btn=QPushButton("Go")
self.go_btn.setMinimumHeight(30)
self.back_btn = QPushButton("<")
self.back_btn.setMinimumHeight(30)
self.forward_btn = QPushButton(">")
self.forward_btn.setMinimumHeight(30)
self.horizontal.addWidget(self.url_bar)
self.horizontal.addWidget(self.go_btn)
self.horizontal.addWidget(self.back_btn)
self.horizontal.addWidget(self.forward_btn)
self.browser=QWebEngineView()
self.go_btn.clicked.connect(lambda: self.navigate(self.url_bar.toPlainText()))
self.back_btn.clicked.connect(self.browser.back)
self.forward_btn.clicked.connect(self.browser.forward)
self.layout.addLayout(self.horizontal)
self.layout.addWidget(self.browser)
self.browser.setUrl(QUrl("http://www.google.com"))
self.window.setLayout(self.layout)
self.window.show()
def navigate(self,url):
if not url.startswith("http"):
url = "http://" + url
self.url_bar.setText(url)
# redirect to your website
if "google.com" in url:
url = "http://stackoverflow.com"
self.browser.setUrl(QUrl(url))
app=QApplication([])
window=MyWebBrowser()
app.exec_()
If I create an html/javascript file called somefile, how will I upload that code to the browser?
Related
I am getting an image file "plot.png" from s3 bucket using the following code
def read_froms3img(image_name):
ep_url=URL
access_id=ID_KEY
access_key=SECRET_KEY
s3_resource = boto3.resource(service_name = "s3",endpoint_url=ep_url, aws_access_key_id=access_id, aws_secret_access_key=access_key)
s3_client = boto3.client(service_name = "s3",endpoint_url=ep_url, aws_access_key_id=access_id , aws_secret_access_key=access_key)
bucket = s3_bucket
bucket = s3_resource.Bucket(bucket)
image = bucket.Object('Images/plot.png')
img_data = image.get().get('Body').read()
return Image.open(io.BytesIO(img_data))
I am calling the above function as below and pass the "contents" to the render_template('data.html)
contents = read_froms3img("plot.png")
return render_template('data.html', form_data = form_data, html_code = html, filename = contents)
And if i do contents.show(), it loads the image in my local.
data.html:
<img src="{{filename}}" height="50%" width="65%">
But the image is not loading in the frontend, if i do inspect element, i can see the below code in the tag
<img src="<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x257583E0DF0>" height="50%" width="65%">
How to display the image in the tag in the html page.
Please help.
Thanks,
Updated Answer
I think you want to allow the web-browser to view an image stored in an S3 bucket. So, make your HTML point to a Flask view like this:
<img src="/S3image/REFERENCE">
where REFERENCE is something that uniquely identifies an image on your S3. Then in your Flask app:
from flask import Response
#app.route('/S3image/<ref>')
def serveS3(ref):
...
... all your code except your 'return' statement
...
return Response(img_data, mimetype='image/png')
Original Answer
You can't return a Python PIL Image object to a web-browser... they don't understand Python. You need to return a PNG image, and you have one already in your variable img_data, so just return that with the appropriate MIME type.
It will look something like:
from flask import Response
....
....
return Response(img_data, mimetype='image/png')
1.) I'am trying to Download the Article PDF Files from multiple web pages to a local folder on the computer. But there is now "Download PDF" button on the web pages. What would be the Quickest and Best way to do this with Selenium ?
2.) One way I have thought of is to use the Keyboard Keys for Print, "Control"- "P", but inside Selenium, none of the Keyboard Keys are working when i run the program. The Code is below,
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome()
driver.maximize_window() # Makes Full Screen of the Window Browser
time.sleep(4)
url = 'https://finance.yahoo.com/news/why-warren-buffett-doesnt-buy 152303112.html'
driver.get(url)
time.sleep(10)
a = ActionChains(driver)
a.key_down(Keys.CONTROL).send_keys('P').key_up(Keys.CONTROL).perform()
You can do that by using ChromeOptions() and have a setting id, origin etc.
Also you can give savefile.default_directory to save the PDF file.
Code:
import time
from selenium import webdriver
import json
Options = webdriver.ChromeOptions()
settings = {
"recentDestinations": [{
"id": "Save as PDF",
"origin": "local",
"account": "",
}],
"selectedDestinationId": "Save as PDF",
"version": 2
}
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings), 'savefile.default_directory': 'C:\\Users\\****\\path\\'}
Options.add_experimental_option('prefs', prefs)
Options.add_argument('--kiosk-printing')
driver_path = r'C:\\Users\\***\\***\\chromedriver.exe'
driver = webdriver.Chrome(options=Options, executable_path=driver_path)
driver.maximize_window() # Makes Full Screen of the Window Browser
time.sleep(4)
url = 'https://finance.yahoo.com/'
driver.get(url)
time.sleep(2)
driver.execute_script('window.print();')
Output:
You should see a PDF file in the directory like this:
Update:
driver_path = r'C:\\Users\\***\***\\chromedriver.exe'
driver = webdriver.Chrome(options=Options, executable_path=driver_path)
Right now I have a code that uses plotly to create a figure
def show_city_frequency(number_of_city = 10):
plot_1 = go.Histogram(
x=dataset[dataset.city.isin(city_count[:number_of_city].index.values)]['city'],
showlegend=False)
## Creating the grid for all the above plots
fig = tls.make_subplots(rows=1, cols=1)
fig.append_trace(plot_1,1,1)
fig['layout'].update(showlegend=True, title="Frequency of cities in the dataset ")
return plot(fig)
I want to incorporate this into a flask function and send it to an html template as a bytes io object using send_file. I was able to do this for a matplotlib just using:
img = io.BytesIO()
plt.plot(x,y, label='Fees Paid')
plt.savefig(img, format='png')
img.seek(0)
return send_file(img, mimetype='image/png')
I've read that I can do basically the same thing except using:
img = plotly.io.to_image(fig, format='png')
img.seek(0)
return send_file(img, mimetype='image/png')
but I can't seem to find where to download plotly.io. I've read that plotly offline doesn't work for Ubuntu so I am wondering if that is what my issue is as well. I am also open to new suggestions of how to send this image dynamically to my html code.
The idea is to collect all soundcloud users' id's (not names) who posted tracks that first letter is e.g. "f" in the period in our case of "past year".
I used filters on soundcloud and got results in the next URL: https://soundcloud.com/search/sounds?q=f&filter.created_at=last_year&filter.genre_or_tag=hip-hop%20%26%20rap
I found the first user's id ("wavey-hefner") in the follow line of html code:
<a class="sound__coverArt" href="/wavey-hefner/foreign" draggable="true">
I want to get every user's id from the whole html.
My code is:
import requests
import re
from bs4 import BeautifulSoup
html = requests.get("https://soundcloud.com/search/sounds?q=f& filter.created_at=last_year&filter.genre_or_tag=hip-hop%20%26%20rap")
soup = BeautifulSoup(html.text, 'html.parser')
for id in soup.findAll("a", {"class" : "sound_coverArt"}):
print (id.get('href'))
It returns nothing :(
The page is rendered in JavaScript. You can use Selenium to render it, first install Selenium:
pip3 install selenium
Then get a driver e.g. https://sites.google.com/a/chromium.org/chromedriver/downloads (if you are on Windows or Mac you can get a headless version of Chrome - Canary if you like) put the driver in your path.
from bs4 import BeautifulSoup
from selenium import webdriver
import time
browser = webdriver.Chrome()
url = ('https://soundcloud.com/search/sounds?q=f& filter.created_at=last_year&filter.genre_or_tag=hip-hop%20%26%20rap')
browser.get(url)
time.sleep(5)
# To make it load more scroll to the bottom of the page (repeat if you want to)
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
html_source = browser.page_source
browser.quit()
soup = BeautifulSoup(html_source, 'html.parser')
for id in soup.findAll("a", {"class" : "sound__coverArt"}):
print (id.get('href'))
Outputs:
/tee-grizzley/from-the-d-to-the-a-feat-lil-yachty
/empire/fat-joe-remy-ma-all-the-way-up-ft-french-montana
/tee-grizzley/first-day-out
/21savage/feel-it
/pluggedsoundz/famous-dex-geek-1
/rodshootinbirds/fairytale-x-rod-da-god
/chancetherapper/finish-line-drown-feat-t-pain-kirk-franklin-eryn-allen-kane-noname
/alkermith/future-low-life-ft-the-weeknd-evol
/javon-woodbridge/fabolous-slim-thick
/hamburgerhelper/feed-the-streets-prod-dequexatron-1000
/rob-neal-139819089/french-montana-lockjaw-remix-ft-gucci-mane-kodak-black
/pluggedsoundz/famous-dex-energy
/ovosoundradiohits/future-ft-drake-used-to-this
/pluggedsoundz/famous
/a-boogie-wit-da-hoodie/fucking-kissing-feat-chris-brown
/wavey-hefner/foreign
/jalensantoy/foreplay
/yvng_swag/fall-in-luv
/rich-the-kid/intro-prod-by-lab-cook
/empire/fat-joe-remy-ma-money-showers-feat-ty-dolla-ign
In this question How can I get a url from Chrome by Python?, it was brought up that you could grab the url from python in pywinauto 0.6. How is it done?
Using inspect.exe (which is mentioned in Getting Started) you can find Chrome's address bar element, and that its parameter "value" contains the current url.
I found two ways to get this url:
from __future__ import print_function
from pywinauto import Desktop
chrome_window = Desktop(backend="uia").window(class_name_re='Chrome')
address_bar_wrapper = chrome_window['Google Chrome'].main.Edit.wrapper_object()
Here's the first way:
url_1 = address_bar_wrapper.legacy_properties()['Value']
Here's the second:
url_2 = address_bar_wrapper.iface_value.CurrentValue
print(url_1)
print(url_2)
Also if protocol is "http" Chrome removes "http://" prefix. U can add sth like:
def format_url(url):
if url and not url.startswith("https://"):
return "http://" + url
return url