簡體   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