脚本专栏 
首页 > 脚本专栏 > 浏览文章

使用Python3编写抓取网页和只抓网页图片的脚本

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

最基本的抓取网页内容的代码实现:

#!/usr/bin/env python 
 
from urllib import urlretrieve 
 
def firstNonBlank(lines): 
  for eachLine in lines: 
    if not eachLine.strip(): 
      continue 
    else: 
      return eachLine 
 
def firstLast(webpage): 
  f = open(webpage) 
  lines = f.readlines() 
  f.close() 
  print firstNonBlank(lines), 
  lines.reverse() 
  print firstNonBlank(lines), 
 
def download(url='http://www',process=firstLast): 
  try: 
    retval = urlretrieve(url)[0] 
  except IOError: 
    retval = None 
  if retval: 
    process(retval) 
 
if __name__ == '__main__': 
  download() 

利用urllib模块,来实现一个网页中针对图片的抓取功能:

import urllib.request 
import socket 
import re 
import sys 
import os 
targetDir = r"C:\Users\elqstux\Desktop\pic" 
def destFile(path): 
  if not os.path.isdir(targetDir): 
    os.mkdir(targetDir) 
  pos = path.rindex('/') 
  t = os.path.join(targetDir, path[pos+1:]) 
  return t 
 
if __name__ == "__main__": 
  hostname = "http://www.douban.com" 
  req = urllib.request.Request(hostname) 
  webpage = urllib.request.urlopen(req) 
  contentBytes = webpage.read() 
  for link, t in set(re.findall(r'(http:[^\s]*"htmlcode">
import urllib.request 
import socket 
import re 
import sys 
import os 
targetDir = r"H:\pic" 
def destFile(path): 
  if not os.path.isdir(targetDir): 
    os.mkdir(targetDir) 
  pos = path.rindex('/') 
  t = os.path.join(targetDir, path[pos+1:]) #会以/作为分隔 
  return t 
 
if __name__ == "__main__": 
  hostname = "http://www.douban.com/" 
  req = urllib.request.Request(hostname) 
  webpage = urllib.request.urlopen(req) 
  contentBytes = webpage.read() 
  match = re.findall(r'(http:[^\s]*?(jpg|png|gif))', str(contentBytes) )#r'(http:[^\s]*?(jpg|png|gif))'中包含两层圆括号,故有两个分组, 
                             #上面会返回列表,括号中匹配的内容才会出现在列表中 
  for picname, picType in match: 
    print(picname) 
    print(picType) 
    
 
''''' 
输出: 
http://img3.douban.com/pics/blank.gif 
gif 
http://img3.douban.com/icon/g111328-1.jpg 
jpg 
http://img3.douban.com/pics/blank.gif 
gif 
http://img3.douban.com/icon/g197523-19.jpg 
jpg 
http://img3.douban.com/pics/blank.gif 
gif 
... 
''' 

上一篇:Python中字典的基础知识归纳小结
下一篇:Python在Windows和在Linux下调用动态链接库的教程
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网