开发者

how to make python 3.x enter text into a web browser

开发者 https://www.devze.com 2023-03-11 08:05 出处:网络
Say I wanted to load google, then automatically enter text into the search bar an开发者_开发问答d press enter all without user input, how would i do that?

Say I wanted to load google, then automatically enter text into the search bar an开发者_开发问答d press enter all without user input, how would i do that?

Edit: while i do need to point it to a specific URL, i want python to be able to enter text regardless of the URL. That's why i need it to be able to enter text into the search on google as opposed to just loading the URL that would come up when you search in google


If I understand properly, you actually want to "control" a specific browser, i.e., open a browser window to a specific URL, rather than having a program parse a web page.

In this case, you can take a look at the subprocess module, with wich you can actually run an external program (e.g., "firefox"), and then check the specification of the browser's command line to understand how to point it to a specific URL. In the case of firefox, you just pass the URL as the first argument. So you could use something like:

from subprocess import Popen
...
Popen(["firefox", "this.is.my.url.com"], ...)

More specifically, if you want to open firefox on the google results for the query string "this is my query" you would use something like:

Popen(["firefox", "http://www.google.com/#q=this+is+my+query"])

Edit: If, instead, you want to start up the browser and then interactively play with the window browser, maybe you should look into desktop automation/messaging frameworks, such as dbus. I do not know exactly if or how, but it should be possible to focus on the browser window, select a specific field and put some text in it.


The best open source project for this is mechanize.

Here's an example similar to what you are talking about:

import mechanize

mech = mechanize.Browser()

try:
    mech.open("http://www.google.com/")
except HTTPError, e:
    sys.exit("%d: %s" % (e.code, e.msg))

# Select the form, fill the fields, and submit
mech.select_form(nr=0)
mech["query"] = "Lester"
try:
    mech.submit()
except HTTPError, e:
    sys.exit("post failed: %d: %s" % (e.code, e.msg))

Check out the examples folder in the source code download for a complete picture of the API. Its extremely well written.

0

精彩评论

暂无评论...
验证码 换一张
取 消