python多进程获取新发地数据

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

class Vegetable_Price(object):
    def __init__(self):
        self.url = "http://www.xinfadi.com.cn/getPriceData.html"
        self.headers = {"User-Agent":"Mozilla/5.0"}

    def get_data_index(self,num):
        data = {
            "limit": "20",
            "current": num,
            "pubDateStartTime": "",
            "pubDateEndTime": "",
            "prodPcatid": "",
            "prodCatid": "",
            "prodName": ""
        }
        resp = requests.post(self.url,data=data,headers=self.headers)
        dict_data = json.loads(resp.text)["list"]
        for data in dict_data:
            prodCat = data["prodCat"]
            prodName = data["prodName"]
            lowPrice = data["lowPrice"]
            avgPrice = data["avgPrice"]
            highPrice = data["highPrice"]
            place = data["place"]
            unitInfo = data["unitInfo"]
            print(prodCat,prodName,lowPrice,avgPrice,highPrice,place,unitInfo)
if __name__ == '__main__':
    spider = Vegetable_Price()
    with ProcessPoolExecutor(20) as q:
        for i in range(1,50):
            q.submit(spider.get_data_index, i)
---------------------------------------------------------------------------------------

努力学习python爬虫ing,多进程多线程爬取数据,数据快多了,期待scrapy框架的学习,听说是神一样存在的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Python中,我们可以使用`multiprocessing`模块来创建多进程。当我们使用多进程时,有时候需要等待子进程完成某些任务并返回结果,然后再继续执行主进程的任务。这时候,我们需要获取进程的返回。 在`multiprocessing`模块中,获取进程的返回有两种方式:`join()`方法和`Queue`队列。 方法一:使用`join()`方法 我们可以在主进程中使用`join()`方法来等待子进程执行完毕,并获取进程的返回。 示例代码: ```python from multiprocessing import Process def func(num): return num * 2 if __name__ == '__main__': p = Process(target=func, args=(10,)) p.start() p.join() result = p.exitcode print(result) ``` 在上面的示例中,我们创建了一个子进程`p`,并传入参数`10`。子进程执行的函数是`func`,该函数会返回传入参数的两倍。在主进程中,我们使用`join()`方法等待子进程执行完毕,并获取进程的返回。`exitcode`属性返回子进程的退出码,也就是子进程执行完毕后的返回。 方法二:使用`Queue`队列 我们可以在主进程中创建一个`Queue`队列,然后将子进程执行的结果放入该队列中,在主进程中从队列中获取进程的返回。 示例代码: ```python from multiprocessing import Process, Queue def func(num, result_queue): result_queue.put(num * 2) if __name__ == '__main__': result_queue = Queue() p = Process(target=func, args=(10, result_queue)) p.start() p.join() result = result_queue.get() print(result) ``` 在上面的示例中,我们创建了一个子进程`p`,并传入参数`10`和一个`Queue`队列`result_queue`。子进程执行的函数是`func`,该函数会将传入参数的两倍放入`result_queue`队列中。在主进程中,我们使用`join()`方法等待子进程执行完毕,并从`result_queue`队列中获取进程的返回。 需要注意的是,在使用`Queue`队列时,我们需要在创建子进程时将队列对象传递给子进程,以便子进程能够将结果放入队列中。同时,获取返回时也需要从队列中获取

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值