scrapy CrawlSpider LinkExtractor如何提取img里的src?

rules = (
        Rule(LinkExtractor(allow=r'bizhi/'), callback='parse_item', follow=True),
        Rule(LinkExtractor(tags=['img'],attrs='src'), callback='download_jpg',follow=False),
    ) 


def download_jpg(self,response):
        id=uuid4().hex
        print(id,'============')
        print(response.url)


#这么写,download_jpg里面没有打印

1.通过修改scrapy源代码调试,LinkExtractor可以提取到img里的src,然后就没有后续了,download_jpg没有被调用

进展:

2.在下载中间件中做一个一个判断,发现并没有对图片链接进行请求

3继续debug

from scrapy.http import HtmlResponse
from scrapy.linkextractors import LinkExtractor

html='''
<!--example2.html-->
<!DOCTYPE html>
<html>
<head>
<title>LinkExtractor</title>
<script type="text/javascript" src="/js/app1.js"></script>
<script type="text/javascript" src="/js/app2.js"></script>
</head>
<body>
    <a href="/home.html">主页</a>
    <a href="123">文档</a>
     <a href="http://www.baidu.com">文档</a>
    <a href="javascript:goToPage('/example.html');return false">案例
        <img src='https://desk-fd.zol-img.com.cn/t_s960x600c5/g5/M00/01/0E/ChMkJ1bKwaWIUfSeAAJDsi1Sfm4AALGbgL0AN0AAkPK796.jpg'>
    </a>
    <a href='https://desk-fd.zol-img.com.cn/t_s960x600c5/g5/M00/01/0F/ChMkJlbKwkmIbK9VAA57yR1wmZgAALGlgIeBm8ADnvh330.jpg'></a>
</body>
</html>

'''
response= HtmlResponse(url='http://example1.com', body=html.encode(), encoding='utf-8')
le = LinkExtractor(tags='a')
le.extract_links(response)

通过构造response,然后构造LinkExtrctor对象,发现href以  .jpg  结尾时,链接不会被抽取,改成  .jp 就可以提取了,说白了,有代码在根据链接的后缀过滤链接

在scrapy源文件下搜索  .jpg 最后定位到scrapy.linkextractor里面的_init_.py

  很明显,忽略的扩展,就是忽略的后缀名。然后回到LinkExtractor的构造函数,有一个一直没注意的参数deny_extensions,就是忽略链接后缀的意思,随便给一个不含.jpg的列表['mp4'],就可以抓取图片了

Rule(LinkExtractor(restrict_css='#bigImg',deny_extensions=['mp4'],tags=['img'],attrs='src'), callback='download_jpg', follow=False),

答案就在linkextracor的构造参数里,谁能知道这地方有坑

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值