I've successfully managed to use win32 COM to grab details about the page numbers of a word document. However, when I try to use mydoc.ActiveWindow.Selection.Information(wdActiveEndPageNumber)
I know that the file has been read into memory properly because mydoc.Content.Text prints out all the content.
I get a "wdActiveEndPageNumber is Not Defined" error. Anyone know why this is happening and how to fix this? And is there some python documentation or am I stuck looking at VB and C# on msdn?
import win32com.client
word = win32com.client.Dispatch("Word.Application")
mydoc=word.DOcuments.Open("path:\\to\\file")
mydoc.ActiveWindow.Selection.Information(wdActiveEndPageNumber)
That's because wdActiveEndPageNumber is a constant that not defined by win32com, until you generate the COM type library from the application. Try this:
from win32com.client.gencache import EnsureDispatch
from win32com.client import constants
word = EnsureDispatch("Word.Application")
mydoc = word.Documents.Open("path:\\to\\file")
mydoc.ActiveWindow.Selection.Information(constants.wdActiveEndPageNumber)
you could use the enumerated number. You can find this using the object browser in word. Just got into the vba editor, press f2 then enter wdActiveEndPageNumber as the search term,. When you select it in the results it wil show you its integer value. Then put that in your code.
Related
I'm using the following code to add a Macro to Excel. I notice that the data / other WorkSheets from the original Excel had dropped completely but the Macro is showing.
This is the code that I am using:
import xlsxwriter
workbooks = xlsxwriter.Workbook('C:\\Users\\user\Desktop\\test.xlsm')
workbooks.add_vba_project('C:\\Users\\user\\Desktop\\vbaProject.bin')
workbooks.close()
I used the link http://xlsxwriter.readthedocs.io/example_macros.html and it seems to be the same from another page https://redoakstrategic.com/pythonexcelmacro/
I wondered if there is another library that I should use for this?
I tried the following link Use Python to Inject Macros into Spreadsheets it seems that here again the data from the original file is overwritten. Not sure if this is a duplicate or not, or if I missed something rather obvious ?
Thanks
Unfortunately, xlsxwriter can't load information from already existing Excel workbooks; it is only used for making new ones. You are overwriting your old workbook with a blank one that has your macros.
If you need to load information, look into openpyxl. It can be used for creating .xlsm files.
One way around it is to create the macro you want in another Excel so we can execute it to affect the other Excel. Then using win32.com it runs the VBA.
enter code here
#import win32com.client
#xl=win32com.client.Dispatch("Excel.Application")
#xl.Workbooks.Open(Filename="C:\\macro.xlsm",ReadOnly=1)
#xl.Application.Run("macro")
#xl = 0
I am trying to code in python to download few data , the code is working for one structure but not for other, its giving me this error which i don't understand. I have written code on sublime text 3 and running it on DOS. Python version using is 2.7.11.
from bs4 import BeautifulSoup
import urllib
import re
url= raw_input("http://physics.iitd.ac.in/content/list-faculty-members")
html=urllib.urlopen(url).read()
soup=BeautifulSoup(html)
table = soup.find("table", attrs={"border":"0","width":"100%","cellpadding":"10"})
head=soup.find("h2",attrs={"class":"title style3"})
ready= table.find_all("tr")
header=head.find("big").find("strong")
datasets=[]
quest=[]
s=[]
test=header.get_text()
quest.append(test)
for b in ready:
x=[td.get_text() for td in b.find_all("td")]
dataset =[strong.get_text() for strong in b.find("td").find("a").find_all("strong")]
datasets.append(dataset)
quest.append(x)
print quest
The fact that it states cannot find the file specified: '' means that you're trying to open a file specified by an empty string!
It's a little hard to help much further since we don't have the code. The code you have included cannot be the code that generated that screenshot since the screenshot would have included a prompt as shown (the argument to the raw_input() call).
Clarifying that point, if that string you appear to have entered was actually entered, there would be no problem.
Calling urlopen() will in turn call FancyUrlOpener.open() and, being a descendant of UrlOpener, that's the function that receives control.
That function will intelligently select the function to use based on the scheme given.
The fact that it's choosing the file scheme rather than the HTTP one, and the fact that the exception complains about the file being an empty string, means that you are not passing in what you think you are.
The error message you're seeing, and the stack trace, can only occur if the following line fails (see open_local_file() here):
stats = os.stat(localname)
The stat call is only for local files, not URLs.
So you should be concentrating your effort: why is the string empty?
The most likely theory is that the code you've given the screenshot for had a different URL in the raw_input prompt and so thats what we're seeing as the prompt in the screenshot.
That would mean you simply pressed ENTER, perhaps thinking it had helpfully provided that URL as a default. That ENTER would then be taken as an emty string which would explain both the scheme selection and the empty string being used as a file name.
I have copy the url to test:
url = "http://www.che.iitb.ac.in/online/people/viewstudents?filter0=**ALL**&op1=&filter1=2010"
urllib.urlopen(url)
In fact, the url can be correctly parsed as "http", but your error msg tells us that your url are parsed as "file", so it is necessary for you to show us your really url or code.
My python version is 2.7.5.
I am trying to scrape a russian website. However i am stuck with trying to convert a russian cyrillic to DateTime object.
Let's take this html piece for example:
<div class="medium-events-list_datetime">22 января весь день</div>
I am able fetch the content of this div by using lxml, i.e:
date = root.xpath('/html/body/div[1]/div/div[2]/text()')[0].strip()
So the relevant part of of this string is 22 января, which is day and a month.
To get this part i am using the .split() method
Now here lies the problem, i am trying to convert this into DateTime.
I try to use DateParser: https://dateparser.readthedocs.org/en/latest/
,which is supposed to support russian.
However it returns None when i pass this string to dateparser.parse()
Did anyone run into similar issue? I am banging my head against the wall on this one. Any help appreciated :)
try running this example:
#coding=utf-8
import dateparser
s = u"22 января"
print dateparser.parse(s)
It should output 2016-01-22 00:00:00
Important: Make sure that you're actually using utf-8 strings. More info: https://www.python.org/dev/peps/pep-0263/
Otherwise your parsing/splitting might be wrong, so try having a look at the results after the split().
I'm trying to get Selenium Webdriver to click x number of links in a table, and I can't get it to work. I can print the links like this:
links = driver.find_elements_by_xpath("//table[2]/tbody/tr/td/p/strong/a")
for i in range(0,len(links)):
print links[i].text
But when I try to do a links[i].click() instead of printing, python throws me an error.
The site uses JSP and the hrefs of the links looks like this "javascript:loadTestResult(169)"
This is a sub/sub-page and not possible to access by direct URL, and the table containing the links are very messy and large so instead of pasting the whole source here I saved the page on this url.
http://wwwe.aftonbladet.se/redaktion/martin/badplats.html
(I'm hunting the 12 blue links in the left column)
Any ideas?
Thanks
Martin
Sorry, to trigger happy.
Simple solution to my own problem:
linkList = driver.find_elements_by_css_selector("a[href*='loadTestResult']")
for i in range(0,len(linkList)):
links = driver.find_elements_by_css_selector("a[href*='loadTestResult']")
links[i].click()
Using TextMate:
Is it possible to assign a shortcut to preview/refresh the currently edited HTML document in, say, Firefox, without having to first hit Save?
I'm looking for the same functionality as TextMate's built-in Web Preview window, but I'd prefer an external browser instead of TextMate's. (Mainly in order to use a JavaScript console such as Firebug for instance).
Would it be possible to pipe the currently unsaved document through the shell and then preview in Firefox. And if so, is there anyone having a TextMate command for this, willing to share it?
Not trivially. The easiest way would be to write the current file to the temp dir, then launch that file.. but, this would break any relative links (images, scripts, CSS files)
Add a bundle:
Input: Entire Document
Output: Discard
Scope Selector: source.html
And the script:
#!/usr/bin/env python2.5
import os
import sys
import random
import tempfile
import subprocess
fname = os.environ.get("TM_FILEPATH", "Untitled %s.html" % random.randint(100, 1000))
fcontent = sys.stdin.read()
fd, name = tempfile.mkstemp()
print name
open(name, "w+").write(fcontent)
print subprocess.Popen(["open", "-a", "Firefox", name]).communicate()
As I said, that wont work with relative resource links, which is probably a big problem.. Another option is to modify the following line of code, from the exiting "Refresh Browsers" command:
osascript <<'APPLESCRIPT'
tell app "Firefox" to Get URL "JavaScript:window.location.reload();" inside window 1
APPLESCRIPT
Instead of having the javascript reload the page, it could clear it, and write the current document using a series of document.write() calls. The problem with this is you can't guarantee the current document is the one you want to replace.. Windows 1 could have changed to another site etc, especially with tabbed browsing..
Finally, an option that doesn't have a huge drawback: Use version control, particularly one of the "distributed" ones, where you don't have to send your changes to a remote server - git, mercurial, darcs, bazaar etc (all have TextMate integration also)
If your code is in version control, it doesn't matter if you save before previewing, you can also always go back to your last-commited version if you break something and lose the undo buffer.
Here's something that you can use and just replace "Safari" with "Firefox":
http://wiki.macromates.com/Main/Howtos#SafariPreview
Open the Bundle Editor (control + option + command + B)
Scroll to the HTML Bundle and expand the tree
Select "Open Document in Running Browser(s)"
Assign Activation Key Equivalent (shortcut)
Close the bundle editor
I don't think this is possible. You can however enable the 'atomic saves' option so every time you alt tab to Firefox your project is saved.
If you ever find a solution to have a proper Firefox live preview, let us know.