繁体   English   中英

python脚本一直在运行

[英]The python script is continuously running

我正在尝试构建一个网络爬虫来提取网页上的所有链接。 我创建了 2 个 python 文件。 (类:scanner.py 和对象:vulnerable-scanner.py)。 当我运行脚本时,它一直在不停地运行。 我无法找到错误。 帮我解决这个问题。

这是我的源代码:

扫描仪.py

import requests
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
import colorama

class Scanner:

    colorama.init()

    def __init__(self, url):
        self.target_url = url
        self.target_links = []

    def is_valid(self, url):
        parsed = urlparse(url)
        return bool(parsed.netloc) and bool(parsed.scheme)

    def get_all_website_links(self, url):

        GREEN = colorama.Fore.GREEN
        WHITE = colorama.Fore.WHITE
        RESET = colorama.Fore.RESET

        urls = set()
        internal_urls = set()
        external_urls = set()
        domain_name = urlparse(url).netloc
        response = requests.get(url)
        soup = BeautifulSoup(response.content, "html.parser")
        for a_tag in soup.findAll("a"):
            href = a_tag.attrs.get("href")
            if href == "" or href is None:
                continue
            href = urljoin(url, href)
            parsed_href = urlparse(href)
            href = parsed_href.scheme + "://" + parsed_href.netloc + parsed_href.path

            if not self.is_valid(href):
                continue
            if href in internal_urls:
                continue
            if domain_name not in href:
                if href not in external_urls:
                    print(f"{WHITE}[*] External link: {href}{RESET}")
                    external_urls.add(href)
                continue
            print(f"{GREEN}[*] Internal link: {href}{RESET}")
            urls.add(href)
            internal_urls.add(href)
        return urls

    def crawl(self, url):
        href_links = self.get_all_website_links(url)
        for link in href_links:
            print(link)
            self.crawl(link)

漏洞扫描器.py

import argu

target_url = "https://hack.me/"
vul_scanner = argu.Scanner(target_url)
vul_scanner.crawl(target_url)

以下部分是(几乎)无限递归:

for link in href_links:
    print(link)
    self.crawl(link)

我相信您在抓取页面中的链接的概念上添加了这一点。 但是你没有设置停止条件。 (尽管目前,似乎您唯一的停止条件是有一个完全没有链接的已爬网页面)。

一种停止条件可能是设置预定义数量的“最大”级别以进行爬网。

在你的 init 函数中是这样的:

def __init__(self, url):
    self.target_url = url
    self.target_links = []
    self.max_parse_levels = 5 #you can go a step further and make this as an input to the constructore (i.e. __init__ function)
    self.cur_parse_levels = 0
.
.
.

def crawl(url):
    if self.cur_parse_levels > self.max_parse_levels:
        return
    for link in href_links:
        print(link)
        self.crawl(link)

暂无
暂无

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

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