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

yipeiwu_com4年前Python爬虫

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

#!/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]*?(jpg|png|gif))', str(contentBytes))): 
    print(link) 
    urllib.request.urlretrieve(link, destFile(link)) 

       

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) 
    
 
''''' 
输出: 
/zb_users/upload/202003/ksmz45lgvqm.gif 
gif 
/zb_users/upload/202003/pjafvx1bwsf.jpg 
jpg 
/zb_users/upload/202003/ksmz45lgvqm.gif 
gif 
/zb_users/upload/202003/sii31lzm24k.jpg 
jpg 
/zb_users/upload/202003/ksmz45lgvqm.gif 
gif 
... 
''' 

相关文章

python爬虫 2019中国好声音评论爬取过程解析

python爬虫 2019中国好声音评论爬取过程解析

2019中国好声音火热开播,作为一名“假粉丝”,这一季每一期都刷过了,尤其刚播出的第六期开始正式的battle。视频视频看完了,那看下大家都是怎样评论的。 1.网页分析部分 本文爬取的...

python爬虫(入门教程、视频教程) 原创

python的版本经过了python2.x和python3.x等版本,无论哪种版本,关于python爬虫相关的知识是融会贯通的,【听图阁-专注于Python设计】关于爬虫这个方便整理过很...

Python 正则表达式爬虫使用案例解析

现在拥有了正则表达式这把神兵利器,我们就可以进行对爬取到的全部网页源代码进行筛选了。 下面我们一起尝试一下爬取内涵段子网站: http://www.neihan8.com/articl...

python 爬取学信网登录页面的例子

python 爬取学信网登录页面的例子

我们以学信网为例爬取个人信息 **如果看不清楚 按照以下步骤:** 1.火狐为例 打开需要登录的网页–> F12 开发者模式 (鼠标右击,点击检查元素)–点击网络 –>需要...

python基于BeautifulSoup实现抓取网页指定内容的方法

本文实例讲述了python基于BeautifulSoup实现抓取网页指定内容的方法。分享给大家供大家参考。具体实现方法如下: # _*_ coding:utf-8 _*_ #xiao...