Python captures web images and places them in a specified folder

Source: Internet
Author: User

Python captures website images and places them in a specified folder

Copy codeThe Code is as follows:
#-*-Coding = UTF-8 -*-
Import urllib2
Import urllib
Import socket
Import OS
Import re
Def Docment ():
Print u'store the file in E: \ Python \ graph (enter a number or letter )'
H = raw_input ()
Path = u'e: \ Python \ fig + str (h)
If not OS. path. exists (path ):
OS. makedirs (path)
Return path
Def getallurl (html ):
Reg = r "a href = '(.*? \. Htm )'"
Allurl = re. compile (reg)
AllList = re. findall (allurl, html)
Return allList
Def getHTML (url ):
Url = url
Req_header = {'user-agent': 'mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv: 1.9.1.6) Gecko/20091201 Firefox/3.5.6 '}
Req_timeout = 20
Html = 'cuowu'
Try:
Req = urllib2.Request (url, None, req_header)
Resp = urllib2.urlopen (req, None, req_timeout)
Html = resp. read ()
Failed t urllib2.URLError as e:
Print e. message
Failed t socket. timeout as e:
GetHTML (url, fu)
Return html
Def getImg (html, path ):
Reg = r 'img class = IMG_show border = 0 src = (.*? \. Jpg )'
Imgre = re. compile (reg)
ImgList = re. findall (imgre, html)
If imgList:
Print 'ghasghg', path
For imgurl in imgList:
Print imgurl
Content2 = urllib2.urlopen (imgurl). read ()
With open (path + '/' + imgurl [-7:], 'wb') as code:
Code. write (content2)
Else:
Return 0
Def getallurl (html ):
Reg = r "a href = '(.*? \. Htm )'"
Allurl = re. compile (reg)
AllList = re. findall (allurl, html)
Return allList
J = 1
I = 0
Print U' enter the URL :'
Ul = raw_input ()
Print u'start download'
Print u'quarter '+ str (j) + U' page'
Html = getHTML (ul)
AllList = getallurl (html)
Path = Docment ()
GetImg (html, path)
While I <len (allList ):
For lis in allList:
L = lis [I]
Url = r 'HTTP: // www. umei. cc/p/gaoqing/rihan/'+ lis
I = I + 1
J = j + 1
Html = getHTML (url)
GetImg (html, path)
Print u'quarter '+ str (j) + U' page'
Else:
Print u'download finished'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.