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

yipeiwu_com5年前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 
... 
''' 

相关文章

基于python3抓取pinpoint应用信息入库

这篇文章主要介绍了基于python3抓取pinpoint应用信息入库,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Pinpoint是...

python爬取百度贴吧前1000页内容(requests库面向对象思想实现)

此程序以李毅吧为例子,以面向对象的设计思想实现爬取保存网页数据,暂时并未用到并发处理,以后有机会的话会加以改善 首先去百度贴吧分析贴吧地址栏中url后的参数,找到分页对应的参数p...

python小技巧之批量抓取美女图片

其中用到urllib2模块和正则表达式模块。下面直接上代码: [/code]#!/usr/bin/env python#-*- coding: utf-8 -*-#通过urllib(2)...

Python探索之爬取电商售卖信息代码示例

网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动的抓取万维网信息的程序或者脚本。 下面有一个示例代码,分享给大家: #...

python抓取网页内容示例分享

复制代码 代码如下:import socketdef open_tcp_socket(remotehost,servicename):    s=socke...