首页 > 解决方案 > 如何解决无法连接'str'和'file'对象错误?

问题描述

当我给它一个文本文件中的子域列表时,我想制作一个 python 脚本来自动截取子域的屏幕截图。

首先,我学习了 python 基础知识,然后当我看到这段代码时开始寻找如何做到这一点:

import requests

BASE = 'https://render-tron.appspot.com/screenshot/'
url = 'https://www.google.com'
path = 'target.jpg'
response = requests.get(BASE + url, stream=True)
# save file, see https://stackoverflow.com/a/13137873/7665691
if response.status_code == 200:
    with open(path, 'wb') as file:
        for chunk in response:
            file.write(chunk)

但是,正如我之前所说,我想给它一个子域列表并一一检查,所以我将这段代码编辑为:

import requests

BASE = 'https://render-tron.appspot.com/screenshot/'
url = open('s.txt','r')
path = 'target.jpg'
response = requests.get(BASE + url, stream=True)
# save file, see https://stackoverflow.com/a/13137873/7665691
if response.status_code == 200:
    with open(path, 'wb') as file:
        for chunk in response:
            file.write(chunk)

但是当我运行它时,它给了我这个错误:

 Traceback (most recent call last):
  File "ping.py", line 7, in <module>
    response = requests.get(BASE + url, stream=True)
TypeError: cannot concatenate 'str' and 'file' objects

这是我运行的代码:

import requests

BASE = 'https://render-tron.appspot.com/screenshot/'
url = open('s.txt','r')
path = 'target.jpg'
response = requests.get(BASE + url, stream=True)
# save file, see https://stackoverflow.com/a/13137873/7665691
if response.status_code == 200:
    with open(path, 'wb') as file:
        for chunk in response:
            file.write(chunk)

标签: pythonpython-2.7

解决方案


正如错误所说,尝试组合字符串和文件对象是没有意义的。

您的意思是访问文件的内容,而不是文件对象本身吗?

如果是这样,请使用:

url = open('s.txt','r').read().strip()

推荐阅读