【网络安全带你练爬虫-100练】第4练:添加异常处理代码

目录

一、异常处理代码:

二、执行结果:

三、完整代码:

四、网络安全小圈子


(当代码越来越长的时候,异常处理代码有时候能起到很好的作用)

(注:其中的cookie需要填自己的)

一、异常处理代码:

(1)try-except搭配:try关键字后面的代码是要监视异常的代码块,except关键字后面的代码是用于处理异常的代码块。

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

(2)异常类型:在except语句中,可以指定要处理的特定异常类型

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

(3)多个except块:可以使用多个except块来处理不同类型的异常。按照从上到下的顺序,第一个匹配的except块将处理异常,而剩余的except块将被忽略

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

(4)else子句:可以在try-except块中添加一个可选的else子句。else子句中的代码将在try块中没有发生任何异常时执行。

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


(5)finally子句:可以在try-except块中添加一个可选的finally子句。无论是否发生异常,finally子句中的代码都将执行。通常在finally块中放置清理代码,例如关闭打开的文件或释放资源。

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



二、执行结果:



三、完整代码:

(注:其中的cookie需要填自己的)

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()

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==



四、网络安全小圈子

README.md · 书半生/网络安全知识体系-实战中心 - 码云 - 开源中国 (gitee.com)https://gitee.com/shubansheng/Treasure_knowledge/blob/master/README.md

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

猜你喜欢

转载自blog.csdn.net/qq_53079406/article/details/131552897