美文网首页Python3自学 爬虫实战
Python---抓取天猫列表数据

Python---抓取天猫列表数据

作者: 杰伊_约翰 | 来源:发表于2019-08-29 17:01 被阅读0次

    在前几天的时候刚爬完各大电商网站,,,疲惫不堪的我又踏上了征程,,

    今天来说说这个淘宝网下的天猫商城,注意是天猫,和普通的淘宝网不一样了,它的列表页数据是静态的,但是它的反爬策略很强,直接就是滑块验证码。说白了就是根据用户的IP限制你的请求了,这时你可以用selenium自动化模拟滑动;也可以尝试使用IP代理池,代理的话找些个免费的先试试,有些网站甚至批量提供。

    再不行的话延时请求,早上我试了一下我每隔30秒请求一次,获取了470条数据;可能是因为间隔的时间太有规律了被封IP了。后来想到了用random去随机延时的请求时间。

    代码如下:

    import requests
    import time
    import random
    from lxml import etree
    
    
    count = 0
    for i in range(60,2370,30):
        url = 'https://list.tmall.com/search_product.htm?spm=a220m.1000858.0.0.42142a68IJUizt&s=' + str(i) + '&q=%CA%D6%BB%FA&sort=s&style=g&from=mallfp..pc_1_searchbutton&type=pc#J_Filter'
    
        headers = {
            'accept-encoding': 'gzip, deflate, br',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',
        }
        s = random.randint(30,240)
        print('本次延迟{}'.format(s))
        time.sleep(s)
        # 延时30秒请求一次,以免访问频率过高的封IP,
        # 也可设置随机的延迟时间,
        # 避免过于规律的等待时间;起步时间不要太低
        response = requests.get(url=url,headers=headers)
        if response.status_code == 200:
            count += 1
            html = response.text
    
            datelist = etree.HTML(html)
            dates = datelist.xpath('//div[@class="product-iWrap"]')
            for date in dates:
                items = {}
                items['title'] = date.xpath('.//p[@class="productTitle"]/a/@title')
                items['price'] = date.xpath('.//p[@class="productPrice"]/em/@title')
                print(items)
    
                with open('Tmspider.csv','w') as f:
                    f.write(str(items))
    
    

    目前的话正在研究使用selenium自动模拟滑块。。。过几天更新一下。。。

    相关文章

      网友评论

        本文标题:Python---抓取天猫列表数据

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