There is a button on the page that when I clicked copies a link. check the below image
I'm trying to store that link in a variable with python selenium this way:
surl=ii.find_element(By.XPATH, f'/html/body/div[1]/div[2]/div[5]/div[1]/div/div/div/section/div/div[2]/div/div[2]/div[1]/div/div/div/div[3]/div[2]/table/tbody/tr[str({row+1})]/td[6]/div/div/span/div/button')
furl = surl.send_keys(Keys.CONTROL + "c")
print(furl)
But I get the result as None. What is the issue here, Could someone help me with this?
Thank you.
By clicking that button the link is copied to the clipboard.
There are several ways to get the text content from clipboard with Python. For example try this:
from tkinter import Tk
surl=ii.find_element(By.XPATH, f'/html/body/div[1]/div[2]/div[5]/div[1]/div/div/div/section/div/div[2]/div/div[2]/div[1]/div/div/div/div[3]/div[2]/table/tbody/tr[str({row+1})]/td[6]/div/div/span/div/button')
surl.click()
link = Tk().clipboard_get()
print(link)
I'm trying to create a script where I copy and paste information from one url to another.
I was able to get the html code using playwright and beautiful soup but was unable to format properly.
For example,
<strong>Autoignition Temperature: </strong>
Using html2text, I was able to convert the above html code to
AutoignitionTemp = ** Autoignition Temperature: **
Which I then paste it into the correct website using this code:
pastePage.frame_locator(
"text=Rich Text Editor, txtContent3Editor toolbarsClipboard/Undo Cut Copy Paste Paste >> iframe").locator(
"body").fill(html2text.html2text(AutoignitionTemp))
However, txt editor does not recognised the ** as bolding and paste the text directly as it is:
Pasted Code:
Is there a way I can format the text properly or paste the html code directly into chrome console?
I have a function checking if a tkinter listbox element is a pdf file. If so, it should be shown via "ShowPdf" in a new window. I only want to view the one pdf I have chosen.
Using the function once works fine. But if I switch to another listbox element and run the function again, the pdf from the first run and the second run are arranged behind each other. So I see the pdf from the first run at first followed by the second pdf. If I run it a third time, then all three pdfs are arranged behind each other etc.
Could you please help me so that only the current pdf is shown?
import tkinter as tk
from tkPDFViewer import tkPDFViewer as pdf
def OnEntryLeft(event):
cur_file=listb.get(listb.curselection())
if (cur_file[-4:]==".pdf" or cur_file[-4:]==".PDF"):
newWindow = tk.Toplevel(root)
pdf.ShowPdf().pdf_view(newWindow,pdf_location=cur_file,width=75,height=100).pack()
else:
messagebox.showinfo("PDF-Check", "NO pdf")
If you look into the source code of tkPDFViwer, you will notice that ShowPdf uses a class variable img_object_li (type list) to store the loaded pages from PDF file. Therefore ShowPdf.img_object_li will hold all the pages from those instances of ShowPdf. I think it is a design bug.
You need to clear the list before loading PDF file:
pdf.ShowPdf.img_object_li.clear() # clear loaded pages
pdf.ShowPdf().pdf_view(newWindow,pdf_location=cur_file,width=75,height=100).pack()
Is it possible to embed rendered HTML output into IPython output?
One way is to use
from IPython.core.display import HTML
HTML('link')
or (IPython multiline cell alias)
%%html
link
Which return a formatted link, but
This link doesn't open a browser with the webpage itself from the console. IPython notebooks support honest rendering, though.
I'm unaware of how to render HTML() object within, say, a list or pandas printed table. You can do df.to_html(), but without making links inside cells.
This output isn't interactive in the PyCharm Python console (because it's not QT).
How can I overcome these shortcomings and make IPython output a bit more interactive?
This seems to work for me:
from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))
The trick is to wrap it in display as well.
Source: http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html
Edit:
from IPython.display import display, HTML
In order to avoid:
DeprecationWarning: Importing display from IPython.core.display is
deprecated since IPython 7.14, please import from IPython display
Some time ago Jupyter Notebooks started stripping JavaScript from HTML content [#3118]. Here are two solutions:
Serving Local HTML
If you want to embed an HTML page with JavaScript on your page now, the easiest thing to do is to save your HTML file to the directory with your notebook and then load the HTML as follows:
from IPython.display import IFrame
IFrame(src='./nice.html', width=700, height=600)
Serving Remote HTML
If you prefer a hosted solution, you can upload your HTML page to an Amazon Web Services "bucket" in S3, change the settings on that bucket so as to make the bucket host a static website, then use an Iframe component in your notebook:
from IPython.display import IFrame
IFrame(src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600)
This will render your HTML content and JavaScript in an iframe, just like you can on any other web page:
<iframe src='https://s3.amazonaws.com/duhaime/blog/visualizations/isolation-forests.html', width=700, height=600></iframe>
Related: While constructing a class, def _repr_html_(self): ... can be used to create a custom HTML representation of its instances:
class Foo:
def _repr_html_(self):
return "Hello <b>World</b>!"
o = Foo()
o
will render as:
Hello World!
For more info refer to IPython's docs.
An advanced example:
from html import escape # Python 3 only :-)
class Todo:
def __init__(self):
self.items = []
def add(self, text, completed):
self.items.append({'text': text, 'completed': completed})
def _repr_html_(self):
return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
"☑" if item['completed'] else "☐",
escape(item['text'])
) for item in self.items))
my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)
my_todo
Will render:
☐ Buy milk
☐ Do homework
☑ Play video games
Expanding on #Harmon above, looks like you can combine the display and print statements together ... if you need. Or, maybe it's easier to just format your entire HTML as one string and then use display. Either way, nice feature.
display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))
Outputs something like this:
Hello, world!
Here's a link:
www.google.com
some more printed text ...
Paragraph text here ...
First, the code:
from random import choices
def random_name(length=6):
return "".join(choices("abcdefghijklmnopqrstuvwxyz", k=length))
# ---
from IPython.display import IFrame, display, HTML
import tempfile
from os import unlink
def display_html_to_frame(html, width=600, height=600):
name = f"temp_{random_name()}.html"
with open(name, "w") as f:
print(html, file=f)
display(IFrame(name, width, height), metadata=dict(isolated=True))
# unlink(name)
def display_html_inline(html):
display(HTML(html, metadata=dict(isolated=True)))
h="<html><b>Hello</b></html>"
display_html_to_iframe(h)
display_html_inline(h)
Some quick notes:
You can generally just use inline HTML for simple items. If you are rendering a framework, like a large JavaScript visualization framework, you may need to use an IFrame. Its hard enough for Jupyter to run in a browser without random HTML embedded.
The strange parameter, metadata=dict(isolated=True) does not isolate the result in an IFrame, as older documentation suggests. It appears to prevent clear-fix from resetting everything. The flag is no longer documented: I just found using it allowed certain display: grid styles to correctly render.
This IFrame solution writes to a temporary file. You could use a data uri as described here but it makes debugging your output difficult. The Jupyter IFrame function does not take a data or srcdoc attribute.
The tempfile
module creations are not sharable to another process, hence the random_name().
If you use the HTML class with an IFrame in it, you get a warning. This may be only once per session.
You can use HTML('Hello, <b>world</b>') at top level of cell and its return value will render. Within a function, use display(HTML(...)) as is done above. This also allows you to mix display and print calls freely.
Oddly, IFrames are indented slightly more than inline HTML.
to do this in a loop, you can do:
display(HTML("".join([f"<a href='{url}'>{url}</a></br>" for url in urls])))
This essentially creates the html text in a loop, and then uses the display(HTML()) construct to display the whole string as HTML
I am trying to save the contents of a Text Editor as a pdf file. The text Editor has been made using PyQt (i didn't make the text Editor), i got the code of the text editor from here. I have done some changes to the editor but that wont be a problem.
After some initial research i found that i need to use ReportLab to publish a pdf file.But i can't find a way to do this .
Does anyone know how this could be accomplished ?
The source code for the Text Editor already has a PDF method, but it is unused, and possibly won't work properly as it stands.
A basic re-write of the method that should work on all platforms, would look like this:
def SavetoPDF(self):
filename = QtGui.QFileDialog.getSaveFileName(self, 'Save to PDF')
if filename:
printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)
printer.setPageSize(QtGui.QPrinter.A4)
printer.setColorMode(QtGui.QPrinter.Color)
printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
printer.setOutputFileName(filename)
self.text.document().print_(printer)
The only other thing you'll need is a menu item to run it, so in Main.initUI just add:
pdfAction = QtGui.QAction("Save to PDF", self)
pdfAction.setStatusTip("Save to PDF")
pdfAction.triggered.connect(self.SavetoPDF)
...
file.addAction(pdfAction)