Hi.
This is my first post, and is about an assignment I've at my college.
An overall description:
We have to make a function, with one argument, the URL. then we have to search the HTML code for any pictures, and to do that I will search for <img and src tags.
All that I can, but then we have to save the pictures local on my harddrive, and make a collage with all the pictures in it. My hindrance right now is the saving part.
For testing the script, I'm using this code:
Code: -
def getImageUrl(urlstring):
-
import urllib
-
connection=urllib.urlopen(urlstring)
-
picture = connection.read()
-
connection.close()
-
curloc = picture.find("img")
-
if curloc <> -1:
-
picloc = picture.find("<src", curloc)
-
picstart = picture.rfind(">",0,picloc)
-
#writefile.open(picture,"wt")
-
pic = open(picture, 'wb').read
-
picture = urllib.urlopen(urlstring)
-
pic.write(picture)
-
pic.close()
-
else:
-
print "There is no pictures in this URL"
I know my code isn't optimized, but I just can't seem to find the function, so it will save my pictures...
In advanced thanks.
Greetings
Public2
4 6671 bartonc 6,596
Recognized Expert Expert
I'm in a rush at the moment and must be brief. For starters, this line is wrong: -
pic = open(picture, 'wb').read
-
probably should be -
pic = open(picture, 'wb')
-
Also, Your post didn't come through quite right. I reformatted. please check it.
More this afternoon
bartonc 6,596
Recognized Expert Expert
I don't see you getting the index of the last tag.
Once you have both the start and end indeces, get a slice of the block like this: -
subBlock = block[start:end]
-
Then go ahead and and write it
The easiest way to retreive the image file is probably to use urlretrieve in the urllib module.
For example if you want to store the thescripts logo from this homepage on your local drive you can do the following: - import urllib
-
urllib.urlretrieve(r'http://www.thescripts.com/images/logo.jpg', r'c:\temp\logo.jpg')
Good luck!
/Fredrik
Hey again.
I finally got finished with my assignment, and thought I would write the code down here. It turned out that we had to make most of the code in Jython, so some of the modules couldn't be used, but I managed anyway. Here is the complete code: -
import urllib
-
from urlparse import urljoin
-
import random
-
-
def makeCollageFromUrl(urlString):
-
listOfImages = getImagesUrl(urlString)
-
imageNames = []
-
for imageUrl in listOfImages:
-
filename = saveImage(imageUrl)
-
imageNames.append(filename)
-
width = 640
-
height = 480
-
picture = makeEmptyPicture(width,height)
-
for imageName in imageNames:
-
p = makePicture(imageName)
-
if p.getWidth()<width and p.getHeight()<height:
-
copyPictureToPicture(p,picture,random.randint(0,width-p.getWidth()),random.randint(0,height-p.getHeight()),0.5)
-
-
picture.show()
-
writePictureTo(picture,r"C:\HTMLCollage.jpg")
-
-
def getImagesUrl(urlString):
-
connection=urllib.urlopen(urlString)
-
getPictures = connection.read()
-
connection.close()
-
executeIndex = 0
-
PicHTMLlist = []
-
while getPictures.find("<img",executeIndex) <> -1:
-
currentPicIndex = getPictures.find("<img",executeIndex)
-
currentSrcIndex = getPictures.find("src=",currentPicIndex)
-
nxtIndex = getPictures.find(">",currentSrcIndex)
-
executeIndex = nxtIndex
-
if getPictures.find("http",currentSrcIndex,nxtIndex)!=-1:
-
end = getPictures.find(" ",currentSrcIndex,nxtIndex)
-
currentPic = getPictures[currentSrcIndex+4:end]
-
currentPic = currentPic.replace('"'," ")
-
currentPic = currentPic.replace("'"," ")
-
repCurrPic = currentPic.lstrip()
-
repCurrPic = repCurrPic.rstrip()
-
if repCurrPic.rfind(".jpg") != -1 or repCurrPic.rfind(".gif") != -1:
-
PicHTMLlist.append(repCurrPic)
-
return PicHTMLlist
-
-
def saveImage(urlString):
-
connection = urllib.urlopen(urlString)
-
getPictures = connection.read()
-
connection.close()
-
sepIndex = urlString.rfind("/")
-
filnavn = urlString[(sepIndex+1):]
-
file = open(filnavn,"wb")
-
file.write(getPictures)
-
file.close()
-
return filnavn
-
-
def copyPictureToPicture(sourcePic,targetPic,offsetX,offsetY, blend):
-
for x in range(1,sourcePic.getWidth()+1):
-
for y in range(1,sourcePic.getHeight()+1):
-
color = sourcePic.getPixel(x,y).getColor()
-
targetPixel = targetPic.getPixel(x+offsetX,y+offsetY)
-
targetColor = targetPixel.getColor()
-
targetPixel.setRed(int(color.getRed()*blend+targetColor.getRed()*blend))
-
targetPixel.setGreen(int(color.getGreen()*blend+targetColor.getGreen()*blend))
-
targetPixel.setBlue(int(color.getBlue()*blend+targetColor.getBlue()*blend))
-
There might be some word in Danish, but most of it is in English. Thanks for your help.
Have a great evening.
Greetings Public2
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Haim Ashkenazi |
last post by:
Hi
I'm writing a script that uses urllib on win98. until now I used python
2.3.x (x < 4) and it worked ok. I re-installed windows and installed
python 2.3.4 and now I get an error when trying to open a url "no host
given":
Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32
Type "copyright", "credits" or "license()" for more information.
|
by: Pater Maximus |
last post by:
I am trying to implement the recipe listed at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/211886
However, I can not get to first base. When I try to run
import urllib
fo=urllib.urlopen("http://www.dictionary.com/")
page = fo.read()
I get:
|
by: Pieter Edelman |
last post by:
Hi all,
I'm trying to submit some data using a POST request to a HTTP server with
BASIC authentication with python, but I can't get it to work. Since it's
driving me completely nuts, so here's my cry for help.
The server is an elog logbook server (http://midas.psi.ch/elog/). It is
protected with a password and an empty username. I can login both using
urllib and urllib2 (suppose the password is "foobar", the logbook is
running on port...
|
by: Timothy Wu |
last post by:
Hi,
I'm trying to fill the form on page
http://www.cbs.dtu.dk/services/TMHMM/ using urllib.
There are two peculiarities. First of all, I am filling in incorrect
key/value pairs in the parameters on purpose because that's the only
way I can get it to work.. For "version" I am suppose to leave it
unchecked, having value of empty string. And for name "outform" I am
suppose to assign it a value of "-short". Instead, I left out
|
by: Mattias |
last post by:
I'm saving pictures on my harddrive from our webcam with GetResponseStream()
.. Everything works fine, but after approximately 1h identical images are
being saved. I checked the webpage but those pictures are still being
refreshed.
Code snippet:
req = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(fullpath);
req.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Return request in a response stream
res =...
| |
by: adolph |
last post by:
Using Access2000, I would like to resize an image then save it to a
new file with the resized size.
I'm taking pictures (JPGs) with my digitial set at 3.2 megs. I've
figured out how to get my access program to find the pictures and show
them as thumbnails so I can add a description and notes. I then
rename and save these pictures to a different location and add a
record to a table with the new file name and location. But the
picture...
|
by: Peder Y |
last post by:
My code is something like this:
---------------
Image img = Image.FromFile("somefile.bmp");
FileStream fStream = new FileStream("someBinaryFile.dat");
BinaryWriter bw = new BinaryWriter(fStream);
img.Save(bw.BaseStream, ImageFormat.Bmp);
|
by: junkdump2861 |
last post by:
Here's the problem: using Netscape 7.1, I type use the view page
source command (url is http://en.wikipedia.org/wiki/Cain) and save the
raw HTML file and it's 67 kb, and has the addresses of all the images
in it. I want the exact same thing from my Python script, but I'm not
getting it. Instead, I get a file only 21 kb that has no image
addresses. Here's the code I use:
import urllib
f =...
|
by: linksterman |
last post by:
i was wondering if there was anyway to load an image into a local variable using urllib or urllib2. i am currently using urllib.urlretrieve method of this, but it has to save each picture before i can use it. so i was wondering if there was any way for me to directly use pictures from the web.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |