检查网站是否具有Python的内容长度
我想编写一个脚本,该脚本将所有IP地址贴在文件中,并显示服务器名称和内容长度的状态。 现在,有些网站不显示内容长度,如果不存在的话,我想编写下一个UP地址。
到目前为止,这是我到目前为止的问题
import requests
import os
#input file name
file_name = input("Enter the name of the file: ")
print("hello")
with open(file_name, 'r') as f:
for line in f:
ip = line.strip()
url = "http://" + ip + "/"
print(ip)
response = requests.get(url)
print(response.status_code, len(response.text))
#print(response.text)
#print(response.headers)
#print(response.headers['Content-Type'])
print(response.headers['Server'])
#print(response.headers['X-Powered-By'])
if response.headers['Content-Length'] == None:
print("Missing Content-Length")
else:
print("this is the content type:", response.headers['Content-Length'])
if ip=="":
print("No host supplied")
,但我仍然遇到错误,说
File "/home/anton/tools/internal_web_tool/web_ip_enumerator.py", line 29, in <module>
if response.headers['Content-Length'] == "":
File "/home/anton/.local/lib/python3.9/site-packages/requests/structures.py", line 54, in __getitem__
return self._store[key.lower()][1]
KeyError: 'content-length'
我如何检查内容长度是否存在?
更正我检查了我正在尝试的IP中的内容长度是否存在,但我崩溃并给我错误,我不知道为什么
I want to write a script that pings all the ip addresses in a file and displays the status the server name and content length.
Now some websites don't display a content length and I want to write if it doesn't exist go on to the next up address.
This is what I have so far
import requests
import os
#input file name
file_name = input("Enter the name of the file: ")
print("hello")
with open(file_name, 'r') as f:
for line in f:
ip = line.strip()
url = "http://" + ip + "/"
print(ip)
response = requests.get(url)
print(response.status_code, len(response.text))
#print(response.text)
#print(response.headers)
#print(response.headers['Content-Type'])
print(response.headers['Server'])
#print(response.headers['X-Powered-By'])
if response.headers['Content-Length'] == None:
print("Missing Content-Length")
else:
print("this is the content type:", response.headers['Content-Length'])
if ip=="":
print("No host supplied")
but I'm still getting an error saying
File "/home/anton/tools/internal_web_tool/web_ip_enumerator.py", line 29, in <module>
if response.headers['Content-Length'] == "":
File "/home/anton/.local/lib/python3.9/site-packages/requests/structures.py", line 54, in __getitem__
return self._store[key.lower()][1]
KeyError: 'content-length'
how can I check if the content length exists or not ?
correction I checked that the content length exists on the ip that I was trying, I but it crashes and gives me the error and I have no idea why
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要检查字典中是否存在密钥,您可以简单地做:
To check if a key exists in a dictionary or not, you can simply do: