美文网首页爬虫基本知识
爬虫简单应用之爬取京东手机图片

爬虫简单应用之爬取京东手机图片

作者: 听城 | 来源:发表于2017-08-08 20:26 被阅读10次
import re
import urllib.request
#只能爬取非延时加载的图片,匹配方式为正则匹配
def craw(url,page):

    #decode之后html字符串将以页面形式展现
    # 正则匹配时需要加上re.S来匹配换行符,因为.默认不匹配换行符
    #也可以不加re.S,这时就不要decode,html中中文以unicode字符展现,
    # 此时html为bytes,需要强转为str进行匹配
    html = urllib.request.urlopen(url).read().decode('utf-8')
    #html = str(html)
    pattern1 = '<div id="plist".*?<div class="page clearfix">'
    str1 = re.compile(pattern1,re.S).findall(html)[0]
    pattern2 = '![](//(.*?\.jpg))'
    imageurls = re.compile(pattern2).findall(str1)
    x = 1
    para2 = str(x)
    for imageurl in imageurls:
        imagename = 'D:/image/'+str(page)+str(x)+'.jpg'
        print(imagename)
        imageurl = 'http://'+imageurl
        try:
            urllib.request.urlretrieve(imageurl,filename=imagename)
        except urllib.error.URLERROR as e:
            if hasattr(e,"code"):
                x+=1
            if hasattr(e,"reason"):
                x+=1
        x+=1


for i in range(1,79):
    url = "https://list.jd.com/list.html?cat=9987,653,655&page="+str(i)
    craw(url,i)

相关文章

网友评论

    本文标题:爬虫简单应用之爬取京东手机图片

    本文链接:https://www.haomeiwen.com/subject/hodxrxtx.html