sprider

本文介绍了一个使用Python编写的简单爬虫,通过requests和lxml库抓取指定网站的商品信息,包括标题、价格、浏览量、销售量和库存,适用于基础网络数据抓取任务。

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

import requests

from lxml import etree

# from fake_useragent import UserAgent

 

class Spider:

    def __init__(self) -> None:

        self.__file = "./goods.txt"

        self.__site = "http://47.94.174.223/index.php?s=/index/goods/index/id/{}.html"

        self.__maxID = 2000

     #   self.__ua = UserAgent()

 

    def __getdata(self, url):

        header_static = {

            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"

        }

    #    header_random = {

     #       "User-Agent": self.__ua.random

      #  }

 

        response = requests.get(url, headers=header_static)

 

        if response.status_code == 200:

            if "资源不存在或已被删除" in response.text:

                print(f"当前url中不存在商品!{url}")

            else:

                html = etree.HTML(response.text)

 

                titles = html.xpath('//h1[@class="detail-title am-margin-bottom-xs"]/text()')

                title = titles[0].strip()

 

                prices = html.xpath('//b[@class="goods-price"]/text()')

                price = prices[0]

 

                tm_count = html.xpath('//span[@class="tm-count"]/text()')

                view_count = tm_count[1]

                sale_count = tm_count[2]

 

                stocks = html.xpath('//span[@class="stock"]/text()')

                stock = stocks[0]

 

                content = f"{title},{price},{view_count},{sale_count},{stock}\n"

 

                return content

 

        else:

            print(f"页面访问失败,状态码:{response.status_code}")

 

    def run(self):

        file = open(self.__file, 'a+', encoding="utf-8")

        content = ""

        for num in range(1, self.__maxID + 1):

            result = self.__getdata(self.__site.format(num))

            if result:

            

                content=str(num) + "," + result

 

                file.write(content)

 

        file.close()

 

if __name__ == "__main__":

    spider = Spider()

    spider.run()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值