结合线程与异步实时获取爬虫爬取状态status

本文介绍了一个银行爬虫模型的实现,模型包括登录、获取信息和爬取数据等状态。通过多线程和异步任务,跟踪模型状态变化,确保爬虫运行效率和稳定性。

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

import time
from threading import Thread
import asyncio

class bankcrawl_model():
    def __init__(self):
        self.status="sleeping"

    def login(self):
        self.status="logging"
        print("this is status:","logging")
        time.sleep(3)
    def getinfo(self):
        self.status="getinfo"
        print("this is status:","getinfo")
        time.sleep(3)
    def crawl(self):
        print("this is status:","crawl")
        self.status="crawl"
        time.sleep(3)
        self.status="sleeping"
        print("this is status:","None")

class ModelThread(Thread):
    def __init__(self,model):
        Thread.__init__(self)
        self.model=model

    def run(self):
        self.model.login()
        self.model.getinfo()
        self.model.crawl()
        
async def get_status(model):
    old = model.status
    print(old)
    while True:
        new=model.status
        if new!=old:
            old=new
            print(new)
        if new=="sleeping":
            break

if __name__=='__main__':
    print("main start!")
    model=bankcrawl_model()
    modellist=[model]
    start_thread(modellist)
    loop=asyncio.get_event_loop()
    loop.run_until_complete(get_status(model))
    print("main end")
构建一个多线程Python爬虫程序来爬取淘宝商品价格,需要考虑以下几个关键步骤和技术点: 参考资源链接:[Python实现的淘宝商品价格爬虫程序](https://wenku.youkuaiyun.com/doc/4mh8br38mb?spm=1055.2569.3001.10343) 1. 分析目标网站:首先需要熟悉淘宝网的页面结构,确定商品价格信息所在的HTML元素,分析网站的反爬虫策略,如是否需要登录、是否有频率限制等。 2. 选择合适的工具库:Python提供了丰富的库来支持爬虫的开发,如requests进行HTTP请求、BeautifulSoup或lxml用于解析HTML、selenium处理JavaScript动态加载的数据等。 3. 多线程编程:Python的threading或asyncio库可以用来实现多线程异步爬取,提高程序的爬取效率。为了防止线程间的资源竞争,可以使用锁(Lock)或线程池(ThreadPoolExecutor)。 4. 反爬虫策略应对:针对淘宝的反爬虫机制,可以采取以下策略: - 使用代理IP:通过代理池轮换IP地址,模拟不同的用户行为。 - 设置请求头:模拟浏览器请求,设置合适的User-Agent、Referer、Accept等字段。 - 控制请求频率:通过设置延时或使用RateLimiter限制短时间内发出的请求数量。 - Cookie管理:可能需要处理登录认证,保存和使用cookies保持会话。 5. 数据存储:爬取到的数据需要存储在数据库或文件中,可以使用SQLite、MySQL等数据库系统,或者将数据保存为CSV、JSON格式。 6. 异常处理:编写爬虫程序时,需要考虑到网络请求可能失败、数据可能解析错误等情况,并编写相应的异常处理代码。 关键代码片段示例: ```python import requests from bs4 import BeautifulSoup from urllib.parse import urlencode import threading import random import time # 商品信息URL构建函数 def build_url(product_id): params = { 'q': '商品名称', # 根据实际情况修改搜索的关键词 'ie': 'utf-8', '卖家店铺id': '0', 'price': '', 'sortType': '3', 'viewType': 'grid', 'nav': '0', 'searchType': 'prod', 'prodType': '0', 'qId': '234324', 'bid': '', 'areaId': '0', 'isprepay': '0', 'prepaytype': '0', 'w': '商品名称', # 商品名称 'pvid': '0', 'version': '4', 'sug': '0', 's': '', 't': '', 't': '', 'match': '', 'order': '', 'ort': '1', 'startPrice': '', 'endPrice': '', 'phrase': '', 'orderType': '0', 'page': '1', 'sca': '2', 'areaId': '0', 'areaIds': '0', 'cat': '0', 'pid': product_id } base_url = '***' return base_url + urlencode(params) # 解析函数 def parse_html(html): soup = BeautifulSoup(html, 'html.parser') # 根据页面结构提取价格信息 # ... # 爬取函数 def fetch_product_price(product_id): url = build_url(product_id) headers = { 'User-Agent': 'Mozilla/5.0 ...' } try: response = requests.get(url, headers=headers) response.raise_for_status() parse_html(response.text) except Exception as e: print(f 参考资源链接:[Python实现的淘宝商品价格爬虫程序](https://wenku.youkuaiyun.com/doc/4mh8br38mb?spm=1055.2569.3001.10343)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值