Python 京东爬取案例

一个爬虫案例,爬取的一个京东网页;

import re          #调用正则表达式模块
import urllib.request   #调用urllib.request模块
def craw(url,page):    #定义函数
    html1=urllib.request.urlopen(url).read()  #读取对应网页的全部代码
    html1=str(html1)
    pat1='<ul class="gl-warp clearfix">.+? id="J_bottomPage">'   #正则表达式1,
    result1=re.compile(pat1).findall(html1)   #把读取的源码按正则表达式1过滤,将中间的商品列表部分留下,其他过滤掉
    result1=result1[0]   #提取的目标图片链接放在一个列表中
    pat2='<img width="220" height="220" data-img="1" data-lazy-img="//(.+?\.jpg)">'   #正则表达式2
    imagelist=re.compile(pat2).findall(result1)  #第二次过滤,提取一个页面中所有想要爬取的图片链接

    x=1

    for imageurl in imagelist:
        imagename="e:/爬虫实验/"+str(page) +str(x)+".jpg"
        imageurl="http://"+imageurl
        try:
            urllib.request.urlretrieve(imageurl,filename=imagename)
        except urllib.error.URLerror as e:
            if hasattr(e,'code'):   #hasattr判断对象中是否存在name属性,当然对于python的对象而言,属性包含变量和方法;有则返回True,没有则返回False
                x+=1
            if hasattr(e,'reason'):
                x+=1
        x+=1
for i in range(1,20):
    url='https://list.jd.com/list.html?cat=670%2C671%2C672&go=0'+str(i)
    craw(url,i)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

#老程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值