How can I get a url from Chrome by Python?

岁酱吖の 提交于 2019-12-06 14:05:16

问题


I'm trying to use Pywinauto to get the Chrome tab's url like this:

(pseudo code)

  1. Press F6 to direct url line.
  2. Ctrl + C to copy url
  3. Get the url from scrapbook
  4. Deal with the url by BS4, Requests, selenium and etc.

I am done with step 1 and stuck at step 2. Again, I don't know how to deal with step 3. Thus, think the method I figure out is incorrect and not efficient. Can anybody suggest what I should do or give me a better way?


回答1:


Just to summarize all the comments in one answer...

pywinauto 0.5.4 is not able to get the URL from Chrome without tricks like TypeKeys and clipboard grabbing. Coming pywinauto 0.6.0 will be able to do that right way.

Just use connect instead of start in case Chrome is already running.

I would also recommend TypeKeys("^c", set_foreground=False) since the URL is already focused after {F6} and focus may switch to the main window.

Application().connect(title=u'How can I get a url from Chrome by Python? - Stack Overflow - Google Chrome', found_index=0) is also better because the title should be unique. In case there are 2 windows found_index=0 or 1 is useful.

To get the clipboard data:

from pywinauto import clipboard
print(clipboard.GetData())



回答2:


If all you want is to paste what you have in the clipboard to a string you could use one of the packages pyperclip or clipboard, which both are pip-installable.

import pyperclip
print(pyperclip.paste())

#or equivalently...
import clipboard
print(clipboard.paste())

will give output 'http://stackoverflow.com/questions/35475103/how-can-i-get-a-url-from-chrome-by-python' (twice...) if I copy the url for this page.



来源:https://stackoverflow.com/questions/35475103/how-can-i-get-a-url-from-chrome-by-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!