I would like to know if its possible to use python to connect to a certain site
(EX: http://www.example.com/python )
and upload an image from the computer. Basically I have a python script that takes images from the webcam. Now after it takes the image how can i send that image to a webpage. If you tell me how to get it to connect to the page I can handle the rest. Thanks in advance!
THIS IS THE PYTHON SCRIPT AT HAND:
from VideoCapture import Device
cam = Device(devnu开发者_StackOverflow中文版m=1)
cam.saveSnapshot('image.jpg', timestamp=3, boldfont=1)
Use urllib2
for this. Basically build up a urllib2.Request
with the URL to the PHP script, and then add_data
to add the image data that you want to submit.
edit: you can follow the examples here, and specifically this example to help understand the full process
I advice you to learn "mechanize" library http://wwwsearch.sourceforge.net/mechanize/ It very easy to use.
This is example from one of my scripts.
def upload_and_get_data(username, password, image_filename):
print image_filename, type(image_filename)
browser = mechanize.Browser()
browser.open("http://itmages.ru/user/login")
form = browser.form = browser.forms().next()
form["LoginForm[username]"] = username
form["LoginForm[password]"] = password
login_response = browser.submit()
# file uploading
form = browser.form = browser.forms().next()
form.add_file(open(image_filename, "r"),
filename=os.path.basename(image_filename))
send_response = browser.submit()
table_regex = re.compile('<table class="stat".*?<input.*?</table>')
table_data_text = table_regex.findall(
send_response.get_data().replace("\n", " "))[0]
table_data_regex = re.compile(
'<tr> *<td.*?<b>([^<]*)</b></td> *<td>(.*?)</td> *</tr>')
table_data = dict(table_data_regex.findall(table_data_text))
return table_data
Of course. Open the file, and use urllib:
imgfile = open("image.jpg", "rb")
urllib.urlopen("http://www.example.com/", imgfile.read())
精彩评论