淘宝爬取商品属性

该博客介绍了如何利用Python的requests库爬取淘宝商品的属性,包括价格、名称、地区、付款人数、店铺和评论数。通过设置headers和cookie来模拟浏览器行为,解析HTML页面中的正则表达式获取数据,并展示爬取结果。
摘要由CSDN通过智能技术生成

#淘宝爬取商品属性
具体代码如下:

import requests 
import re
def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        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) #名称
        ite=re.findall(r'\"item_loc\"\:\".*?\"',html) #地区
        sal=re.findall(r'\"view_sales\"\:\".*?\"',html) #付款人数
        nic=re.findall(r'\"nick\"\:\".*?\"',html) #店铺
        lo=re.findall(r'\"comment_count\"\:\".*?\"',html) #评论数
        for i in range(len(plt)):
            price=eval(plt[i].split(":")[1])
            title=eval(tlt[i].split(":")[1])
            item=eval(ite[i].split(":")[1])
            sales=eval(sal[i].split(":")[1])
            nick=eval(nic[i].split(":")[1])
            loc=eval(lo[i].split(":")[1])
            ilt.append([price,title,item,sales,nick,loc])
            
    except:
        print("")
def printGoodsList(ilt):
    tplt = "{:4}\t{:8}\t{:16}\t{:16}\t{:16}\t{:16}\t{:16}"
    print(tplt.format("序号","价格","商品名称","地区","付款人数","店铺","评论数"))
    count=0
    for g in ilt:
        count=count+1
        print(tplt.format(count,g[0],g[1],g[2],g[3],g[4],g[5]))
    print("")
def main():
    goods="血压计" #可任意输入商品名称
    depth=1 #页面数
    start_url="https://s.taobao.com/search?q="+goods
    infoList=[]
    for i in range(depth):
        try:
            url=start_url +"&s="+str(44*i)
            headers={
                "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
                "cookie": "选取自己的Cookie"
                }
            html=requests.get(url,headers=headers)
            parsePage(infoList,html.text)
        except:
            continue
    printGoodsList(infoList)
main()

爬取结果:
在这里插入图片描述

1.request库的安装:
Win平台:“以管理员身份运行” cmd ,执行 pip install requests。
request库的安装测试:

import requests
r=requests.get("http://www.baidu.com")
print(r.status_code)
#输出 200
r.text
print(r.text)

2.cookie 的查找
登录你的淘宝账号
获取方法:按F12,打开开发者工具,然后按ctrl+F,在搜索页面任意搜索一个物品名字,如血压计。接着双击图上指出的位置,在header下面找到cookie的内容。
在这里插入图片描述

使用Selenium进行淘宝商品爬取,通常涉及以下几个步骤: 1. **安装依赖**: 首先需要安装Selenium库,这是一个浏览器自动化工具,可以模拟用户操作。另外,由于Selenium需要与特定的浏览器驱动(如ChromeDriver、FirefoxDriver等)配合使用,你也需要下载对应版本的浏览器驱动。 2. **启动浏览器**: 导入`webdriver`模块,比如`from selenium import webdriver`,然后通过`webdriver.Chrome()`或`webdriver.Firefox()`创建一个新的浏览器实例。 3. **打开淘宝网站**: 调用`browser.get('https://www.taobao.com')`打开淘宝主页。 4. **定位元素**: Selenium通过XPath、CSS选择器或ID等属性定位网页中的元素。例如,你可以找到搜索框并输入关键词:`search_box = browser.find_element_by_id('q')`。 5. **提交搜索**: 利用`search_box.send_keys(keyword)`发送搜索请求。 6. **查找商品列表**: 通过定位元素,找到商品列表区域,并遍历查找商品信息。 7. **解析数据**: 一旦找到商品信息,利用如BeautifulSoup这样的HTML解析库,提取标题、价格、图片链接等数据。 8. **保存数据**: 将抓取到的数据存储到CSV、JSON文件,或者数据库中。 ```python # 示例代码片段 from selenium import webdriver from bs4 import BeautifulSoup def crawl_taobao(keyword): # ...其他步骤... browser.find_element_by_id('su').click() # 提交搜索 page_source = browser.page_source soup = BeautifulSoup(page_source, 'html.parser') products = soup.select('.product-title') # 假设商品标题类名为.product-title for product in products: title = product.text.strip() price = product.find('span', class_='price').text # 类名假设为.price img_url = product.find('img')['src'] # 存储数据 save_data(title, price, img_url) # 实际使用时记得处理异常和浏览器关闭 if __name__ == '__main__': keyword = input("请输入你要搜索的商品关键字:") try: crawl_taobao(keyword) finally: browser.quit() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值