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

2018-04-27 15:46:54 浏览数 (1)

代码语言:javascript复制
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)

0 人点赞