抓取淘宝某类商品名称和价格

该博客介绍了一种使用Python进行网络爬虫的方法,通过requests和re库抓取淘宝页面上特定商品(口红)的价格和名称。首先定义了一个getHTMLText函数用于获取网页内容,然后用parsePage函数解析网页,通过正则表达式提取价格和名称信息。最后,printGoodList函数将结果以表格形式展示。爬虫遍历了搜索结果的多个页面(深度为3)以获取更多商品信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
import re
import time


def getHTMLText(url):
    try:
        r = requests.get(url, timeout = 30)#设定超时时间
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return print("解析网页失败")
def parsePage(li, html):
    try:
        counts = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)#正则获取价格
        names = re.findall(r'\"raw_title\"\:\".*?\"',html)#正则获取名字
        for i in range(len(counts)):
            price = eval(counts[i].split(':')[1])#以:分割,获取价格,同时删除引号等符号
            title = eval(names[i].split(':')[1])
            li.append([price, title])
    except:
        print("爬取失败")


def printGoodList(lis):
    tplt = "{:4}\t{:8}\t{:16}"
    print(tplt.format("序号","价格","产品信息"))
    num = 1
    for g in lis:
        num = num + 1
        print(tplt.format(num, g[0], g[1]))

if __name__ == '__main__':
    goods = "口红"
    depth = 3
    start_url = 'http://s.taobao.com/search?q=' + goods
    list = []
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(44*i)
            html = getHTMLText(url)
            parsePage(list,html)
        except:
            continue
    printGoodList(list)

编写一个爬取淘宝商品信息的爬虫,我们需要先确定使用的API或者工具。由于淘宝官方并未开放大规模的数据抓取API,我们通常会借助一些公开的淘宝商品详情页解析库,如`tianmao spider`或者手动解析HTML。这里我将以手动解析为例,给出一个基本的Python脚本,使用`requests``beautifulsoup4`库,不过需要注意,真实环境中需要遵守淘宝的robots.txt协议以及可能的使用限制。 首先确保已安装所需的库: ```bash pip install requests beautifulsoup4 pandas ``` 下面是一个简化的示例,爬取商品列表并保存到CSV文件中: ```python import requests from bs4 import BeautifulSoup import csv import time def get_html(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } response = requests.get(url, headers=headers) if response.status_code == 200: return response.text else: return None def parse_item(html): soup = BeautifulSoup(html, 'html.parser') items = [] for item in soup.find_all('li', class_='gl-item'): # 假设商品信息在类名为'main'的ul下,每个商品是一个li元素 name = item.find('h3', class_='p-name').text.strip() price = item.find('span', class_='p-price').text.strip() sale_num = item.find('em', class_='item-num').text.strip() rating_num = item.find('i', class_='score-i').find_next_sibling().text.strip() # 假设评分在i元素后的兄弟节点 items.append([name, price, sale_num, rating_num]) return items def save_to_csv(items, filename): with open(filename, 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['商品名称', '价格', '销量', '评价数']) writer.writerows(items) def main(): base_url = "https://list.tmall.com/search.htm?q={}&s=0&style=all&stock=1&sort=sale-desc&page=" # 需替换为你想要搜索的商品类别 start_page = 1 end_page = 10 for page in range(start_page, end_page + 1): url = base_url.format('你想搜的商品关键词') + str(page) html = get_html(url) if html is not None: items = parse_item(html) save_to_csv(items, f'thobao_{page}_items.csv') time.sleep(2) # 爬虫速度控制,避免过于频繁 else: print(f"无法获取第{page}页数据,可能已被阻止") main() ``` 注意:这个例子仅作展示,实际上淘宝的商品详情页面结构可能会不断变化,而且真实环境中抓取可能涉及到反爬虫策略,因此在实际操作时需要谨慎处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值