由于淘宝对于爬虫有很强的反爬机制,因此我们需要使用一些技巧来规避反爬。以下是一个简单的爬虫代码,可以爬取淘宝近半年没有活跃的店铺链接并保存到txt文件中。

首先,我们需要安装必要的库,包括requests和BeautifulSoup4。可以使用以下命令进行安装:

pip install requests
pip install beautifulsoup4

接下来,我们需要先通过浏览器登录淘宝,然后复制浏览器中的cookies信息,以便我们的爬虫可以模拟登录状态。将cookies信息保存在一个名为cookies.txt的文件中。

然后,我们可以编写如下的爬虫代码:

import requests
from bs4 import BeautifulSoup
import time

# 设置请求头
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.36',
}

# 读取cookies
cookies = {}
with open('cookies.txt', 'r') as f:
    for line in f.read().split(';'):
        name, value = line.strip().split('=', 1)
        cookies[name] = value

# 获取店铺列表
shop_list = []
for i in range(1, 201):  # 爬取前200页
    url = f'https://s.taobao.com/search?q=&s={i * 44}&initiative_id=staobaoz_{time.strftime("%Y%m%d", time.localtime())}&sort=sale-desc'
    response = requests.get(url, headers=headers, cookies=cookies)
    soup = BeautifulSoup(response.text, 'html.parser')
    items = soup.find_all('div', {'class': 'item J_MouserOnverReq'})
    if len(items) == 0:
        break
    for item in items:
        shop_link = item.find('a', {'class': 'shopname J_MouseEneterLeave J_ShopInfo'}).get('href')
        shop_list.append(shop_link)

# 检查店铺是否活跃,将未活跃的店铺链接保存到txt文件中
inactive_shop_list = []
for shop_link in shop_list:
    response = requests.get(shop_link, headers=headers, cookies=cookies)
    soup = BeautifulSoup(response.text, 'html.parser')
    last_active_time = soup.find('div', {'class': 'seller-info'}).find_all('span')[-1].text
    if '天前' in last_active_time and int(last_active_time.split('天前')[0]) > 180:  # 检查是否近半年没有活跃
        inactive_shop_list.append(shop_link)

with open('inactive_shop_links.txt', 'w') as f:
    for shop_link in inactive_shop_list:
        f.write(shop_link + '\n')

在上述代码中,我们首先读取cookies文件中的信息,并设置请求头。然后,我们通过循环爬取淘宝前200页的店铺列表,并将店铺链接保存在一个列表中。

接下来,我们检查每个店铺的最近活跃时间,如果该店铺近半年没有活跃,则将其链接保存到另一个列表中。

最后,我们将保存了未活跃店铺链接的列表写入到txt文件中。

需要注意的是,由于淘宝的反爬机制较为严格,如果爬取太频繁或者数据量过大,可能会被封禁IP或账号。因此,我们需要控制爬取速度,比如使用time.sleep()函数在每次请求之间暂停一段时间,以模拟人类的行为。同时,我们也可以尝试使用代理IP或者分布式爬虫等技术来规避反爬机制。

写一个Python爬虫爬取淘宝近半年没有活跃的店铺将近半年没有活跃的店铺链接保存到txt文件中

原文地址: https://www.cveoy.top/t/topic/gRM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录