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.

2
  • 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. Commented May 3, 2018 at 22:53
  • yes, it was only a typo, the actual code is slightly different. Commented May 3, 2018 at 23:09

1 Answer 1

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}')
Sign up to request clarification or add additional context in comments.

3 Comments

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).
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.
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.