网络爬虫爬取淘宝页面商品信息

网络爬虫爬取淘宝页面商品信息

最近在MOOC上看嵩老师的网络爬虫课程,按照老师的写法并不能进行爬取,遇到了一个问题,就是关于如何“绕开”淘宝登录界面,正确的爬取相关信息。通过百度找到了答案,在此记录一下。

注意:你需要先用自己的淘宝登录一下然后获得cookie才是有效的。

针对以上问题主要的代码是

kv = {'cookie':'','user-agent':'Mozilla/5,0'}
r = requests.get(url,headers=kv,timeout=30)

会在最后附上全代码(不含cookie)

那么问题的关键就是cookie的获取

(1)首先需要用到Google chrome浏览器登录淘宝
(2)然后就是按F12键进入开发者模式
(3)按照以下图片进行点击
在这里插入图片描述

以下是“完整”代码:

import requests
import re

def getHTMLText(url):
    kv = {'cookie':'','user-agent':'Mozilla/5,0'}
    try:
        r = requests.get(url,headers=kv,timeout=30)
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

def parsePage(ilt,html):
    try:
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
        for i in range(len(plt)):
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            ilt.append([price,title])
    except:
        print("")

def printGoodsList(ilt):
    tplt = "\t{:^4}{:^8}\t{:^16}" 
    count = 0
    print(tplt.format("序号",'价格','名称'))
    for i in ilt:
        count = count + 1
        print(tplt.format(count,i[0],i[1]))
        
def main():
    goods='书包'
    depth = 2
    infoilt = []
    start_url = 'https://s.taobao.com/search?q='+goods
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(44*i)
            html = getHTMLText(url)
            parsePage(infoilt,html)
        except:
            continue
    printGoodsList(infoilt)
    
main()    

PS:该文章仅用于学术探讨。/笑脸

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值