本文實例講述了Python使用正則表達式抓取網頁圖片的方法。分享給大家供大家參考,具體如下:
#!/usr/bin/pythonimport reimport urllib#獲取網頁信息def getHtml(url): page = urllib.urlopen(url) html = page.read() return htmldef getImg(html):#匹配網頁中的圖片 reg = r'src="(.*?/.jpg)" alt' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'%s.jpg' % x) x+=1html = getHtml("http://photo.bitauto.com/?WT.mc_id=360tpdq")print getImg(html)
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關于Python相關內容可查看本站專題:《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答