2

I'm trying to open a specific location within an HTML file with python, but it doesn't work.

The code is

import webbrowser

url = '~\docs\index.html#api.method_name'
webbrowser.open(f'file:///{url}')

This code opens the file in the browser, but the url '~\docs\index.html'. It doesn't take me to the part location of api.method_name. But if I copy and paste the ulr in a web browser, it works.

I have already tried changing the hash sign to %23, but it didn't work either.

Damodar Dahal
  • 559
  • 4
  • 16
llulai
  • 627
  • 1
  • 6
  • 9
  • 1
    That code won't do what you say it does. You've got a typo (`ulr` vs. `url`). Please make sure you copy and paste your code so it _exactly_ represents the problem you are having. We have no way of knowing which typos are relevant and which aren't. – ChrisGPT was on strike May 03 '18 at 22:53
  • yes, it was only a typo, the actual code is slightly different. – llulai May 03 '18 at 23:09

1 Answers1

0

The problem looks like caused by the use of \. You should be using / for traversing file system. The following code works on my system:

import webbrowser

url = '~/docs/index.html#api.method_name'
webbrowser.open(f'file:///{url}')
Damodar Dahal
  • 559
  • 4
  • 16
  • doesn't seem to work in this way either. (please keep in mind that I'm trying to access a file in the computer (in windows), not a url in the web). – llulai May 03 '18 at 23:07
  • In Python strings, backslash is used to escape characters with special meanings. However, `\d` and `\i` don't have a special meaning, so this particular string is interpreted as typed. Using a forward slash **or** a double backslash instead of single backslash for file/location navigation is safest though, as `\n`, `\a`, `\v`, `\x` and many other characters do have a special meaning. – Campbell McDiarmid May 03 '18 at 23:19
  • Try `webbrowser.get("C:/Program Files/Google/Chrome/Application/chrome.exe %s").open(f'file:///{url}')`. It works on windows 7. (Note that you might need to change the Chrome path). – Damodar Dahal May 03 '18 at 23:20