繁体   English   中英

Python语句好像没有效果

[英]Python statement seems to have no effect

我正在尝试编写一个函数,如果文本大于 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

在 if 块和log_error函数调用中也有语法错误,应该是log_errors ,像这样修复它。

with closing(get(url, stream=True)) as resp:
     if is_good_response(resp):
         if len(resp.text) > 0:
             print('Pass')
         else: 
             print('Fail')
     return None

修改后的代码在这里..

from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup as soup
import requests
import time


def url_check(url, multiplier=1):
    """
    Makes http request. If HTML or XML format is found, will return text, otherwise return none
    """
    try:
        with requests.get(url) as fb:
            if is_good_response(fb):
                if len(fb.text) > 0:
                    print('Pass')
                else: 
                    print('Fail')
            return fb.text

    except RequestException as e:
        log_errors('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 = str(input('Enter the year: '))
    raw = url_check(f"https://www.basketball-reference.com/leagues/NBA_{year}_totals.html")
    html = soup(raw, 'html.parser')
# Gets headers from table
    headers = [th.getText()
               for th in html.findAll('tr', limit=2)[0].findAll('th')]
    headers = [tag.replace('%', '') for tag in headers[1:]]
    print(headers)


def log_errors(e):
    print(e)

# Invoke the program
get_data()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM