我正在尝试编写一个函数来检查网站是否有效,如果文本大于0,则返回“ Pass”,但是这样做很难。我正在使用Pycharm,我的代码行[[elif str(len(resp.text))> 0给我带来麻烦。以下是整个代码。我目前正在转换为字符串,但是我也尝试了不使用字符串功能的情况。预先感谢。
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup as soup
def url_check(url, multiplier=1):
"""
Makes http request. If HTML or XML format is found, will return text, otherwise return none
"""
time.sleep(2*multiplier)
try:
with closing(get(url, stream=True)) as resp:
if is_good_response(resp):
elif str(len(resp.text)) > 0
print('Pass')
else:
print('Fail')
return None
except RequestException as e:
log_error('Error during request to {0} : {1}'.format(url, str(e)))
return None
def is_good_response(resp):
"""
Will return True if response is HTML. Will return False if otherwise
"""
content_type = resp.headers['Content-Type'].lower()
return(resp.status_code == 200
and content_type is not None
and content_type.find('html')> -1)
def get_data(year):
year = input()
raw = url_check("https://www.basketball-reference.com/leagues/NBA_{}_totals.html".format(year))
html = soup(raw, 'html.parser')
#Gets headers from table
soup.findAll('tr', limit=2)
headers = [th.getText() for th in soup .findAll('tr',limit=2)[0].findAll('th')]
headers = headers [1:]
headers
def log_errors(e):
print(e)
str
比较作为数字的0,您应该将数字与数字进行比较。尝试不使用str
。len(resp.text)>0