python - 如何解决无法连接'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)
解决方案
正如错误所说,尝试组合字符串和文件对象是没有意义的。
您的意思是访问文件的内容,而不是文件对象本身吗?
如果是这样,请使用:
url = open('s.txt','r').read().strip()
推荐阅读
- kibana - 如何在 Kibana、Grafana 等任何工具中为磁盘中的结构化日志文件创建仪表板
- android - 自定义布局不会改变其相对于其他元素的位置
- javascript - JavaScript 表格未显示在屏幕上
- python - 使用 BeatifulSoup 类 == 解析 HTML 并且标题包含
- google-colaboratory - KeyBERT 包不适用于 Google Colab
- gradle-kotlin-dsl - 如何将`apply(plugin = "java")`和idea插件放入外部gradle.kts文件
- python - 在 selenium python 中向下滚动二级页面
- java - Spring ElasticSearch:组合多个查询时出现问题
- reactjs - 如何使用 Typescript 在反应函数中传递参数
- reactjs - 为什么 SwiperJS React 的鼠标滚轮功能不起作用?