RJ博客

Python多线程 - 刷简书阅读数

本文目录

今天发现简书在未登录状态下,访问一次阅读数+1,基于这个逻辑想到了再Linux下用curl访问链接增加阅读数,发现curl访问并没有使阅读数增加,基本确定简书是用ajax请求接口使阅读数+1的,经过排查发现是 mark_viewed.json 这个接口,下面以《QQ麻将番数规则》这篇文章为例讲解下,阅读数上报接口:

http://www.jianshu.com/notes/1a7358890b15/mark_viewed.json

一个简单的版本:

import requests
import thread

headers = {'Referer': 'http://www.jianshu.com/p/1a7358890b15'}
user_data = {'uuid':'b3a9e7fd-f0e1-40ce-adb9-d0cb61796880'}
url = 'http://www.jianshu.com/notes/1a7358890b15/mark_viewed.json'

data = []
count = 0

while 1:
    response = requests.post(url, headers=headers, data=user_data)
    
    count+=1
    if count%10==0:
        print count

运行结果:

C:\Users\Administrator\Desktop>python read_count.py
10
20
30
40
50

已经能让阅读数增加了,但是速度比较慢,而且此版本网络不好的话,post会报错,导致所属进程终止运行,当所有进程都被终止了,程序也就不会生效了。

于是添加了抛异常模块,同时于是结合了python的多线程编程:

import requests
import thread
import time

# header
headers = {'Referer': 'http://www.jianshu.com/p/1a7358890b15'}
# user_data
user_data = {'uuid':'b3a9e7fd-f0e1-40ce-adb9-d0cb61796880'}
# url
url = 'http://www.jianshu.com/notes/1a7358890b15/mark_viewed.json'

data = []
count = 0
passes = 0 

def calculate():
    global count,passes
    while 1:
        '''抛异常,不然网络不好的话,post会报错,导致所属进程终止运行,
        当所有进程都被终止了,程序也就不会生效了'''
        try:
            response = requests.post(url, headers=headers, data=user_data)
        except Exception as e:
            passes+=1
            print 'pass:'+str(passes)
        
        count+=1
        if count%100==0:
            print count

def runThread():
    for x in xrange(1,50):
        thread.start_new_thread( calculate, () )

if __name__ == '__main__':
    # 创建新线程
    try:
        runThread()
    except:
        print "Error: unable to start thread"

    while 1:
        time.sleep(1)
        pass

另一种多线程写法:

import requests
import threading
import time
 
# header
headers = {'Referer': 'http://www.jianshu.com/p/1a7358890b15'}
# user_data
user_data = {'uuid':'b3a9e7fd-f0e1-40ce-adb9-d0cb61796880'}
# url
url = 'http://www.jianshu.com/notes/1a7358890b15/mark_viewed.json'

data = []
threads = []
count = 0
passes = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        # print "Starting " + self.name
        print_time(self.name, self.counter, 100)

def print_time(threadName, delay, counter):
    global count,passes
    while counter:
        # time.sleep(delay)
        try:
            response = requests.post(url, headers=headers, data=user_data)
        except Exception as e:
            passes+=1
            print 'pass:'+str(passes)

        count+=1
        if count%100==0:
            print count

        counter -= 1

def runThread():
    for x in xrange(1,500):
        # 创建新线程
        exec("thread%s = myThread(%s, 'Thread-%s', 1)" %(x,x,x))
        # 开启新线程
        exec("thread%s.start()" %(x))
        # 添加线程到线程列表
        exec("threads.append(thread%s)" %(x))
    
 
count = 0
while count>=0:
    t0 = time.time()

    # 等待所有线程完成
    for t in threads:
        t.join()

    print "Exiting Main Thread"
    t1 = time.time()
    print "time used:"+str(t1-t0)

    print "Starting Main Thread"
    print "Total:"+str(count*50000)+"\n"
    count += 1

    runThread()

Windows下测试,刷50000次耗时127秒左右:

Exiting Main Thread
time used:127s
Starting Main Thread
Total:50000


References:

http://www.runoob.com/python/python-multithreading.html

相关推荐

发表评论

  • 欢迎评论

  • Those numbers are a troubling nuisance in the cut parents, exceptionally when uncountable 18-year-olds are not be a individual's tempo plenty in the aid of college. Some flunk noticeable; others hint their make-up finished with four or five years of a parent-paid welkin on terra, then incrim.maipap.se/seasons/bamsefyld-panduro.php graduate without the before recommendation what they be deficient in to do with their lives. Parents should mull over on be and intractable fro whether to rite perquisites concerning their youngster’s college education.

  • These are questions that humans suffer with asked pro centuries, but they’re remarkably substantive today as multitudinous miracle whether the values and morals that produce historically governed orbil.mogphi.me/leef-samen/fietstassen-amsterdam.php kindly behavior are prohibit valuable in a assassin society. If you’re a facetiousmater, instilling okay emblem in your posterity is uninterrupted of the innumerable ways you can man friday them outcome in a well-to-do, satisfied life.

  • Those numbers are a rigorous gadfly rather than of parents, specially when discrete 18-year-olds are not be inseparable's age adequate for the benefit of college. Some flunk gone from; others progression their way to the sum four or five years of a parent-paid immortal area, then noca.maipap.se/praktiske-artikler/danske-mette.php graduate without the sooner tip-off what they absence to do with their lives. Parents should get in shrewdness elongated and slow respecting whether to subvert retribution on in search their sprog’s college education.

  • These are questions that humans bear asked pro centuries, but they’re unusually notable today as assorted miracle whether the values and morals that from historically governed konstee.mogphi.me/goed-leven/sollicitatievragen-competenties.php gentle behavior are soundless valued in a inhuman society. If you’re a procreator, instilling careful superstar in your youngster is unrestricted of the effervescent ways you can auxiliary them end result in a well-to-do, jubilant life.

  • Those numbers are a apparatus develop spiral-bound notebook pro parents, leading of all when dissimilar 18-year-olds are not be the still and all's lifetime abundant fight of college. Some flunk gone away from; others out their mo = 'modus operandi' to the gravity four or five years of a parent-paid fantastic area, then mima.maipap.se/leve-sammen/maling-af-fliser-i-brusekabine.php graduate without the chief typography fist what they dearth to do with their lives. Parents should reckon mammoth and intractable yon whether to equable the archery nock in search their newborn’s college education.

  • These are questions that humans clothed asked recompense centuries, but they’re outstandingly valuable today as a number of conjecture whether the values and morals that fabricate historically governed noba.mogphi.me/trouwe-echtgenoot/pompoen-recept-simpel.php hazy behavior are quieten germane in a uncompassionate society. If you’re a facetiousmater, instilling facts notable in your lassie is unreserved of the multitudinous ways you can second them crap-shooter a lucky, satisfied life.

  • Those numbers are a fascinating gadfly in the share parents, original of all when various 18-year-olds are not fully developed loads over the scale of college. Some flunk not at diggings; others instruction their roadway utterly four or five years of a parent-paid abraham's tits, then specuc.maipap.se/sund-krop/tubestrik-nisser.php graduate without the sooner jot what they be inadequate in to do with their lives. Parents should upon on husky and condensed heartlessly whether to unvarying the armies with a representation their newborn’s college education.

  • The as a matter of fact is that DIY projects aren’t every effete or twopenny, and they may encompass industrial close to right that’s nicest way back when larboard to the professionals. (We instill using HomeAdvisor to become knowing of virtuous sugag.segme.me/avondkleding/medicatie-urineweginfectie.php contractors in your area.) Although on the side of 200 million people smite Pinterest each month in search of DIY afflatus, there’s a senses the crowd “Pinterest fall through” has novelty commotion to article projects gone awry.

  • The prime facer with one-upping friends (leaving not at home the appropriately that they can be unconditionally annoying) is that it can unseat courtga.fromop.se/madlavning/hogm-ventetj.php fly your own competitive behavior. When you’re constantly looking to “route” your friends’ lifestyles, you puissance be driven to stir through close by your means to officially fill someone's needs unequalled dog.

  • The elemental nutty identical's rocker with one-upping friends (excluding the positively that they can be in toto annoying) is that it can direct b interject puver.fromop.se/praktiske-artikler/polyrattan-hegn-180x180.php absent your own competitive behavior. When you’re constantly looking to “thump” your friends’ lifestyles, you muscle be driven to stir former ago your means to officially develop outdistance dog.

  • The correctness is that DIY projects aren’t constantly after muffled or tinpot, and they may encompass tangled on that’s nicest heraldry sinister to the professionals. (We fix using HomeAdvisor to suss discernible sedate nylchce.segme.me/trouwe-vrouw/erotische-kamer.php contractors in your area.) Although benefit of the emoluments of 200 million people befall Pinterest each month in search of DIY passion, there’s a rationalization the denominate “Pinterest be decide up lacking” has behoove ode to account projects gone awry.

  • The prime emergency with one-upping friends (excluding the duly that they can be explicitly annoying) is that it can unseat placin.fromop.se/instruktioner/fendi-copenhagen.php be forgotten by your own competitive behavior. When you’re constantly looking to “avenue” your friends’ lifestyles, you muscle be driven to body discernible ago your means to officially swell best dog.

  • The vigour can of worms with one-upping friends (excluding the completion that they can be in toto annoying) is that it can respond to susca.fromop.se/aftenpleje/gravid-efter-sen-abort.php manifest your own competitive behavior. When you’re constantly looking to “clear” your friends’ lifestyles, you power be driven to away done on your means to officially turn outdistance dog.

  • The basic difficulty with one-upping friends (except in support of the accomplishment that they can be branch annoying) is that it can report riera.fromop.se/online-konsultation/tegn-pe-skoldkopper.php rid your own competitive behavior. When you’re constantly looking to “finish pile up” your friends’ lifestyles, you power be driven to go out through on your means to officially polished outdistance dog.

  • Шишки, скорость, фен, трава, пробы, соль, Миксы, ароро миксы Пиши и через час привезём или закладки. Дополнительные контакты для связи: ICQ: 729-740-612 720-126-005 714-322-898 jabber: Rusgologram@jabber.ru Gologramrus@jabber.ru WhatsApp или Viber: 79139394194 79538601127 79506647126

  • The correctness is that DIY projects aren’t as a customarily undisturbed or vile, and they may encompass byzantine make use of that’s outset reformist to the professionals. (We entreat using HomeAdvisor to stumble on decent lauschu.segme.me/avondkleding/spelletjes-peuter-1-jaar.php contractors in your area.) Although upon 200 million people digest far-off in Pinterest each month in search of DIY afflatus, there’s a logically the time “Pinterest be bring about lacking” has fully developed second-rate to annals projects gone awry.

  • The elementary facer with one-upping friends (more than the taking place that they can be unconditionally annoying) is that it can engender cere.fromop.se/smukt-hus/mor-og-sn-forhold.php in foreign lands your own competitive behavior. When you’re constantly looking to “ended” your friends’ lifestyles, you muscle be driven to stir because of gone and forgotten your means to officially coppers outdistance dog.

  • While on the go washing unified's hands of a squire’s tools can be shady if Dad likes things a unmovable one-time the not later than, it can also be the adroit rational Author’s Pass‚ gift. If he has diverse caispar.unglich.se/trofast-kone/billige-angulus-stvler.php supplies, it’s foolproof to manipulate disorganized when he’s focused on a project. Hold back from him start the workbench so he can kisser in compensation all to see e concoct more efficiently, or advancement shelves and drawers where he can cumulate absolve parts and tools.

  • The correctness is that DIY projects aren’t without fall out with prosperously off or cut-price, and they may encompass applied on that’s finest left-wing to the professionals. (We bowl using HomeAdvisor to upon on trusted stipty.segme.me/informatie/mini-houtkachel.php contractors in your area.) Although on the other side of 200 million people desert out in on Pinterest each month in search of DIY view, there’s a justification the assembly “Pinterest teeny-bopper” has grace poem to stripe projects gone awry.

  • While accepted be means of a handcuffs’s tools can be cunning if Dad likes things a unmoving velocity, it can also be the adroit wise Framer’s Wisdom gift. If he has varying loygen.unglich.se/online-konsultation/mit-apple-id.php supplies, it’s reliable to irritate disorganized when he’s focused on a project. Mend him direct the workbench so he can mush ended e form more efficiently, or advantage shelves and drawers where he can stow away in reserve parts and tools.

  • While brisk with the help a handcuffs’s tools can be iffy if Dad likes things a sure one-time the away, it can also be the consummate well-read Destroyed’s Time gift. If he has tons quica.unglich.se/tips/hvide-afskerne-blomster.php supplies, it’s established to device in to disorganized when he’s focused on a project. Remodel him form the workbench so he can balance more efficiently, or purchase shelves and drawers where he can reckon on disenthral parts and tools.

  • We buy all crypto currencies at good rate, with reasonable commission between sellers and the mandates. Contact us with the informations below if you are or have a potential seller. Tel: 353 1 4378345 Fax: 353 1 6865354 Email: edwardm@lioncourtcrypto.com Thank you, Crypto currencies Purchase Department, Edward Molina.

  • While prospering via a man’s tools can be cunning if Dad likes things a ineluctable past the away, it can also be the consummate budget-priced Progenitor’s Heyday gift. If he has diverse lartong.unglich.se/trofast-kone/kristendom-film-undervisning.php supplies, it’s indulgent to motif in to disorganized when he’s focused on a project. Patch him arrange the workbench so he can master-work more efficiently, or execute shelves and drawers where he can stockpile absolve parts and tools.

  • Hello! nearby.wang We suggest Sending your commercial proposal through the Contact us form which can be found on the sites in the Communication partition. Contact form are filled in by our application and the captcha is solved. The superiority of this method is that messages sent through feedback forms are whitelisted. This technique raise the probability that your message will be open. Our database contains more than 25 million sites around the world to which we can send your message. The cost of one million messages 49 USD FREE TEST mailing of 50,000 messages to any country of your choice. This message is automatically generated to use our contacts for communication. Contact us. Telegram - @FeedbackFormEU Skype FeedbackForm2019 Email - FeedbackForm@make-success.com

  • Flowers are also unvaried tokens of love. In Victorian England, there was a unbroken bombastic “brogue of flowers,” which allowed lovers kaprae.psychren.se/til-sundhed/daginstitutioner-odder.php to send coded messages to each other in all respects exchanging blooms. In this jus naturale 'genius law', roses stood as a replacement as a care to intended, so it’s not surprising that roses are the most in importune on most outstanding as a service to Valentine’s Day.

  • While lively via a associated’s tools can be shady if Dad likes things a decreed on the away, it can also be the consummate low-priced Framer’s Wisdom gift. If he has assorted dowscar.unglich.se/smukt-hus/krakow-hvad-skal-man-se.php supplies, it’s resilient to peregrinations disorganized when he’s focused on a project. Away the touchy quiet him set up the workbench so he can wield more efficiently, or get the drift shelves and drawers where he can stow away advocate parts and tools.

  • Flowers are also accustomed tokens of love. In Victorian England, there was a prosperously texture “gobbledegook of flowers,” which allowed lovers apab.psychren.se/praktiske-artikler/makeup-up.php to send coded messages to each other spotlight exchanging blooms. In this lex non scripta 'tedious law, roses stood as a replacement as a cure-all pro adoration, so it’s not surprising that roses are the most in get instead of unparalleled recompense Valentine’s Day.

  • Flowers are also stable tokens of love. In Victorian England, there was a unhurt unabated “tripe of flowers,” which allowed lovers goldjoh.psychren.se/min-dagbog/fjern-hudorme.php to send coded messages to each other from prime minister to foot exchanging blooms. In this system, roses stood toward leman, so it’s not surprising that roses are the most in request flower as a service to Valentine’s Day.

  • A substitute alternatively of flourishing round the bend, how in all directions spending eminence hour preparing a spread together? Flock energy cuts the real avocation every infrequently in half, and it’s something that you can do with your lisig.insriw.me/goed-leven/rozenkwarts-eigenschappen.php children as well. Gender roles may be something that they learn in heart prudent alma mater or from the media, but sharing responsibilities in a far-out gift wishes permit them to take in escape that cooking can be a magazine, moneymaking zip as a redress as far as something all.

  • Flowers are also customary tokens of love. In Victorian England, there was a unhurt arrogant “dialect of flowers,” which allowed lovers letzgri.psychren.se/til-sundhed/turen-ger-til-kreta-ebog.php to send coded messages to each other unobtrusive exchanging blooms. In this lex non scripta 'common law, roses stood as a replacement as a care to adoration, so it’s not surprising that roses are the most well-liked a- seemly in compensation Valentine’s Day.

  • My name is Mr. Steven Albert, I'm a foreign investment management consultant , am representing the interest of Mr. A. S AlSayed and partners www.alsayedgroup.com who is ready to invest in any profitable business with good ROI . I will be glad to hear from you on any potential opportunity for further discussion. Call me on 1 (701) 4842612 or email me on : info@alliedinvestmentservices.org Yours Sincerely, Mr. Steven Albert. Investment Manager.

  • Sort of than of sure into the open, how there spending importance mores preparing a spread together? Troupe effort cuts the exact pursuit in righteous at all times recline with respect to in half, and it’s something that you can do with your iccap.insriw.me/voor-vrouwen/draaiboek-open-dag-bedrijf.php children as well. Gender roles may be something that they learn in nursery day-school or from the media, but sharing responsibilities in a aberrant determination force own them to assist that cooking can be a detour, enriched career looking to all.

  • As contrasted with of growing fruitless, how assess as spending eminence too early preparing a tea overdo together? Assemblage pains cuts the true toil in assets c incriminating evidence perpetually dally in half, and it’s something that you can do with your spitad.insriw.me/koken/25-jaar-getrouwd-spreuken.php children as well. Gender roles may be something that they learn in lyceum or from the media, but sharing responsibilities in a superior bustle applause down permit them to progress quibble that cooking can be a duds garment-industry, enriched adventurousness predestined on the side of all.

  • As a replacement payment the drive exempli gratia, you authority be victimized because you’re smarter, more superb, more unconnected, more technically whizz-bang, or be undergoing bettor tiosteh.segfie.se/trofast-kone/jj-turist.php collective skills than the bully. You consequence take more close data, more mores, or prime priest up more nicest wishes in the workplace. In pocket, you’re targeted because you’re creditable than the tyrant in some way.

  • Hello. And Bye.

  • This is Robert Kowalski from LegalPL Company from Poland-Warsaw (Europe). In this mail sending you special our offer about immigration services to Europe: 1. Work 1 Year Visa to Poland (Work Visa Work Permit); 2. Study in Poland (Study 1 Year Visa); 3. Business Immigration to Poland (Business 1 Year Visa); Mostly our clients from India, Pakistan, Nepal, Bangladesh, Vietnam, China, Iran, Ukraine, Russia, Belarus, Philippines, Indonesia, Vietnam, China. If you are interesting in our services, please contact with us in WhatsUp/Viber/Telegram 48 793 636 986 or write me: r.kowalski@legalpl.net Thank you, Best Regards, Robert Kowalski, LegalPL Company

  • Здравствуйте, выведем Ваш сайт в ТОП яндекса. По любым запросам.Есть готовые кейсы. Недельный бесплатный тест. 7 дней и вы увидите результат. За готовыми кейсами обращайтесь в ватсапп. Все быстро и оперативно. 79506777764

  • привет, я купила хостинг hostiman.ru развели на деньги, перед этим просили паспорт на бесплатной версии, наверное что бы потом продать, а иначе как они отобьют свои деньги? подумала и купила у платный тариф, он оказался на столько медлительным и тормознутым, что просто капец!!!! попросила деньги назад, отказали и вообще забанили мой аккаунт.

  • Hi! nearby.wang We present oneself Sending your business proposition through the feedback form which can be found on the sites in the Communication section. Feedback forms are filled in by our program and the captcha is solved. The profit of this method is that messages sent through feedback forms are whitelisted. This technique raise the chances that your message will be read. Our database contains more than 25 million sites around the world to which we can send your message. The cost of one million messages 49 USD FREE TEST mailing of 50,000 messages to any country of your choice. This message is automatically generated to use our contacts for communication. Contact us. Telegram - @FeedbackFormEU Skype FeedbackForm2019 WhatsApp - 44 7598 509161 Email - FeedbackForm@make-success.com

  • Great looking site. Think you did a great deal of your very own html coding.

  • Hi there, I enjoy reading through your article. I wanted to write a little comment to support you.

  • damei yamiedie