使用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 
... 
''' 

相关文章

python爬虫获取淘宝天猫商品详细参数

首先我是从淘宝进去,爬取了按销量排序的所有(100页)女装的列表信息按综合、销量分别爬取淘宝女装列表信息,然后导出前100商品的 link,爬取其详细信息。这些商品有淘宝的,也有天猫的,...

python爬虫获取小区经纬度以及结构化地址

本文实例为大家分享了python爬虫获取小区经纬度、地址的具体代码,供大家参考,具体内容如下 通过小区名称利用百度api可以获取小区的地址以及经纬度,但是由于api返回的值中的地址形式不...

python scrapy爬虫代码及填坑

python scrapy爬虫代码及填坑

涉及到详情页爬取 目录结构: kaoshi_bqg.py import scrapy from scrapy.spiders import Rule from scrapy.lin...

在Python3中使用asyncio库进行快速数据抓取的教程

web数据抓取是一个经常在python的讨论中出现的主题。有很多方法可以用来进行web数据抓取,然而其中好像并没有一个最好的办法。有一些如scrapy这样十分成熟的框架,更多的则是像me...

用python的requests第三方模块抓取王者荣耀所有英雄的皮肤实例

用python的requests第三方模块抓取王者荣耀所有英雄的皮肤实例

本文使用python的第三方模块requests爬取王者荣耀所有英雄的图片,并将图片按每个英雄为一个目录存入文件夹中,方便用作桌面壁纸 下面时具体的代码,已通过python3.6测试,可...