简单的python网络爬虫实现

  学了差不多一星期python,目的有两个,第一,作为一名CS的学生需要懂得一门脚本语言。第二,那就是网络爬虫啦。
  此次爬虫很简单,就是爬斗鱼直播平台上的美女主播的图片 网址是https://www.douyu.com/directory/game/yz 。直接贴代码:

import urllib2
import urllib
import re
import time



def getHtml(url):
    request = urllib2.Request(url)
    request.add_header('User-Agent','Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) 
    AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36')
    response = urllib2.urlopen(request)
    html=response.read()
    return html
def getImage(html):
     imglist=re.findall(r'data-original="(.*?\.(jpg|jpeg))"',html)
     print(len(imglist))
     path =""
     x=0
     for img in imglist:
         urllib.urlretrieve(img[0],"/home/qiracle/douyu/"+str(x)+"."+img[1])
         x+=1
         time.sleep(1)



html =getHtml("https://www.douyu.com/directory/game/yz")
getImage(html)

最终爬到的结果如下:

结果

文章目录
|