【问题标题】:why request stop after a certain time in python?为什么在python中请求停止一段时间后?
【发布时间】:2021-01-20 23:36:21
【问题描述】:

我有这个代码,它的功能是发送一个Jetta类型的请求,从请求中带上文本,从文本文件中读取网站链接,问题是发送300或500个请求后,脚本停止而没有显示任何错误,它只是停止工作??

import requests

sites = open(r'site.txt', 'r', encoding="utf8").readlines()

l_site = []

for i in sites:
    l_site.append(i)


for x in len(l_site):
    result = requests.get(f'{site}', allow_redirects=True).text
    open('result.txt', 'a').write(f'{result}\n')

【问题讨论】:

  • 您是否在调试器中单步执行它以查看它停止时发生的确切情况?
  • 您的代码应该在第一次请求之前失败并出现 NameError。
  • 当您应该在循环之前打开一次文件时,在循环中重复打开文件是一种不好的形式。

标签: python python-3.x python-requests request


【解决方案1】:

如果我理解正确,这就是你想要的:

  1. 读自site.txt
  2. 如果http请求成功,将响应载荷附加到result.txt
  3. 如果 http 请求由于超时而失败,则将结果与 url 附加到另一个文件中

这是一段运行的代码。请注意,如果您想捕获更多类型的错误,可以更改 except 部分。

import requests

URLS_FILE = 'site.txt'
RESULT_FILE = 'result.txt'
ERRORS_FILE = 'result-error.txt'

def handle_url(url: str, result_file, error_file): 
    try:
        # 10 seconds timeout, not download time, but time to get an HTTP response
        content = requests.get(url, allow_redirects=True, timeout=10)
        result_file.write(f'{content.text}\n')
    except requests.exceptions.ConnectTimeout as e:
        error_file.write(f'{url}: {e}\n')




with open(URLS_FILE, 'r', encoding="utf8") as f:
    with open(RESULT_FILE, 'a') as rf:
        with open(ERRORS_FILE, 'a') as ef:
            for url in f.readlines():
                handle_url(url, rf, ef)

【讨论】:

    【解决方案2】:

    我认为你的函数比你在这里输入的要多,因为我看不到 site 变量是在哪里创建的。

    您可以按照这些思路做一些事情,以更好地了解它在哪里停止。

    import requests
    
    sites = open(r'site.txt', 'r', encoding="utf8").readlines()
    
    l_site = [s for s in sites]
    
    with open('result.txt', 'a') as fb:
    
        for site in l_site:
            try:
                print(f"Processing {site}")
                result = requests.get(f'{site}', allow_redirects=True).text
                fb.write(f'{result}\n')
            except Exception as e:
                raise e
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      相关资源
      最近更新 更多