Python脚本使用多处理和请求库提前退出,不会出错

2024-04-26 11:57:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它使用CloudScraper库解析来自某个网站的一些数据,CloudScraper库提供了与requests库相同的功能,但是如果它遇到CloudFlare挑战,它会解决它并成功加载页面。 该函数获取一个字符串输入,然后向网站发出请求。所有这些都是在多线程中使用多处理库完成的。但是,我有一个奇怪的问题,我从来没有过。它运行良好,直到随机它只是退出早期没有错误,没有完成工作。有时它可以在2k次迭代中退出,有时它可以达到150k。我的列表的总长度是450k

我在Windows1064位上,使用Python3.7.464位和CloudScraper和BeautifulSoup4库的最新版本。我在用多处理.pool.pool作为一种多重处理的方式。我也试过用多处理池线程池,但问题依然存在。你知道吗

我的导入:

import cloudscraper
import bs4
from multiprocessing.pool import ThreadPool
import multiprocessing as mp
import logging
import os

为列表中的每个项执行的函数:

def inthread(line):
    global counter
    pid = os.getpid()
    print(f'{pid} start')
    print(f'{pid} Username: {line}')
    user = line.strip()    #   <--------- Eventually exits after this line
    html = requests.post('post_url',
    'nick='+user+'&key='+key+'&submit=%D0%9E%D1%82%D0%BF%D1%80%D0%B0%D0%B2%D0%B8%D1%82%D1%8C',
    headers={'Content-Type': 'application/x-www-form-urlencoded'})
    print(f'{pid} post request')
    #print(html.text)
    soup = bs4.BeautifulSoup(html.text, 'html.parser')
    print(f"{pid} init soup parser")
    for elem in soup.find_all('h4'):
        elem2 = elem.find_all('br')
        for el in elem2:
            if el.next == None:
                print(f"{pid} el.next == None")
                break
            if 'Database' in el.next and 'Password' in el.previous:
                passwd = el.previous.split(':')[1][1::]
                print(f'{pid} Password: %s' % passwd)
                if len(passwd) == 32:
                    #print('%s:%s\n' % (user,passwd))
                    o_md5.write('%s:%s\n' % (user,passwd))
                    print(f'{pid} write to file')
                    o_md5.flush()
                    print(f'{pid} flush file')
                    break
                elif 'Plain' in el.next:
                    #print('%s:%s\n' % (user,passwd))
                    o_plain.write('%s:%s\n' % (user,passwd))
                    print(f'{pid} write to file')
                    o_plain.flush()
                    print(f'{pid} flush file')
                    break
                elif len(passwd) == 86:
                    #print('%s:%s\n' % (user,passwd))
                    o_sha.write('%s:%s\n' % (user,passwd))
                    print(f'{pid} write to file')
                    o_sha.flush()
                    print(f'{pid} flush file')
                    break
    counter += 1
    print(f'{pid} Count: {counter}')

此函数中的请求是CloudScraper类的对象 它是这样创造的:

requests = cloudscraper.create_scraper(interpreter='js2py')

我希望脚本会遍历整个列表,但它会随机退出。你知道吗


Tags: inimporthtmllinepidelfilewrite