How to get the current URL from Chrome using pywin

2019-07-16 04:40发布

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?

1条回答
够拽才男人
2楼-- · 2019-07-16 05:30

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
查看更多
登录 后发表回答