[Network security takes you to practice reptiles - 100 exercises] Practice 4: Add exception handling code

Table of contents

1. Exception handling code:

2. Execution results:

3. Complete code:

4. Small circle of network security


 

(When the code is getting longer and longer, the exception handling code can sometimes play a very good role)

(Note: The cookie needs to be filled by yourself)

1. Exception handling code:

(1) Try-except collocation: The code behind the try keyword is a code block to monitor exceptions, and the code behind the except keyword is a code block for handling exceptions.

try:
    # 可能引发异常的代码块
except ExceptionType:
    # 处理特定类型的异常的代码块

(2) Exception type: In the except statement, you can specify the specific exception type to be handled

try:
    # 可能引发异常的代码块
except ZeroDivisionError:
    # 处理 ZeroDivisionError 异常的代码块

(3) Multiple except blocks: Multiple except blocks can be used to handle different types of exceptions. In order from top to bottom, the first matching except block will handle the exception, and the remaining except blocks will be ignored

try:
    # 可能引发异常的代码块
except ExceptionType1:
    # 处理 ExceptionType1 异常的代码块
except ExceptionType2:
    # 处理 ExceptionType2 异常的代码块

(4) else clause: An optional else clause can be added in the try-except block. The code in the else clause will be executed if no exception occurs in the try block.

try:
    # 可能引发异常的代码块
except ExceptionType:
    # 处理异常的代码块
else:
    # 如果没有发生异常,则执行的代码块


(5) finally clause: An optional finally clause can be added in the try-except block. The code in the finally clause will execute whether or not an exception occurs. Cleanup code, such as closing open files or releasing resources, is usually placed in a finally block.

try:
    # 可能引发异常的代码块
except ExceptionType:
    # 处理异常的代码块
finally:
    # 无论是否发生异常,都会执行的代码块
wAAACH5BAEKAAAAAAAAAABAAEAAAICRAEAOw==



2. Execution results:



3. Complete code:

(Note: The cookie needs to be filled by yourself)

import requests
from bs4 import BeautifulSoup

def get_TYC_info():
    try:
        html = get_page(TYC_url)
        soup = BeautifulSoup(html, 'lxml')
        GS_list = soup.find('div', attrs={'class': 'index_list-wrap___axcs'})
        GS_items = GS_list.find_all('div', attrs={'class': 'index_search-box__7YVh6'})
        for item in GS_items:
            title = item.find('div', attrs={'class': 'index_name__qEdWi'}).a.span.text
            link = item.a['href']
            company_type = item.find('div', attrs={'class': 'index_tag-list__wePh_'}).find_all('div', attrs={'class': 'index_tag-common__edIee'})
            tpye_texts = [element.text for element in company_type]
            money = item.find('div', attrs={'class': 'index_info-col__UVcZb index_narrow__QeZfV'}).span.text


            print(title.strip(),link,tpye_texts,money)
    except Exception as e:
        print("An error occurred:", str(e))

def get_page(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/44.0.2403.89 Chrome/44.0.2403.89 Safari/537.36',
            'Cookie':'!!!!!!!!!!'
}
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        return response.text
    except requests.exceptions.RequestException as e:
        print("An error occurred while making the request:", str(e))
    except Exception as e:
        print("An error occurred:", str(e))
    return ""


if __name__ == '__main__':
        TYC_url = "https://www.tianyancha.com/search?key=&base=hub&city=wuhan&cacheCode=00420100V2020&sessionNo=1688108233.45545222"
        get_TYC_info()

wAAACH5BAEKAAAAAAAAAABAAEAAAICRAEAOw==



4. Small circle of network security

README.md Book Bansheng/Network Security Knowledge System-Practice Center-Code Cloud-Open Source China (gitee.com) https://gitee.com/shubansheng/Treasure_knowledge/blob/master/README.md

GitHub - BLACKxZONE/Treasure_knowledgehttps://github.com/BLACKxZONE/Treasure_knowledge

Guess you like

Origin blog.csdn.net/qq_53079406/article/details/131552897