属性错误:'set'对象没有属性'popleft'

2024-06-12 01:39:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个网站地图生成器。简而言之,我给它一个链接,它在网站上寻找更多的链接等等。你知道吗

为了避免任何长的边缘链,我想我应该创建一个blocked_sites.txt,我可以从中读取并将我的unprocessed_urls与之进行比较,然后删除所有包含阻止程序的项。你知道吗

我的问题是,我太天真了,我以为我可以简单地做一些集合/列表比较和删除,viola做了,但是问题更大,主要是collection *deque*

代码

我首先定义我的分层url,它是用户输入,然后我将它添加到一个que中:

 # a queue of urls to be crawled
unprocessed_urls = deque([starting_url])

接下来我将开始处理我的URL:

    # process urls one by one from unprocessed_url queue until queue is empty
while len(unprocessed_urls):

    # Remove unwanted items
    unprocessed_urls = {url for url in unprocessed_urls if not any(blocker in url for blocker in blockers)} <-- THIS IS THE PROBLEM

    # move next url from the queue to the set of processed urls
    newurl = unprocessed_urls.popleft()
    processed_urls.add(newurl)

    # extract base url to resolve relative links
    parts = urlsplit(newurl)
    base_url = "{0.scheme}://{0.netloc}".format(parts)
    if parts.scheme !='mailto' and parts.scheme !='#':
        path = newurl[:newurl.rfind('/')+1] if '/' in parts.path else newurl
    else:
        continue

    # get url's content
    print(Fore.CYAN + "Crawling URL %s" % newurl + Fore.WHITE) 
    try:       
        response = requests.get(newurl, timeout=3)

所以问题是,程序不应该进入大型网站,我已经明确定义了被阻止,比如:

# Blockers
blockers = set(line.strip() for line in open('blocked_sites.txt'))

通过使用建议的从不需要的行中剥离unprocessed_urls的方法,我使用这个行位(代码中也指出了这一点):

# Remove unwanted items
unprocessed_urls = {url for url in unprocessed_urls if not any(blocker in url for blocker in blockers)}

因此,我们发现自己在这里:

AttributeError: 'set' object has no attribute 'popleft'

我能想到的是,通过尝试删除不需要的项目,它会以某种方式改变collection的类型

我真的不知道如何从这里开始前进。你知道吗


Tags: toinurlforifqueue网站urls
1条回答
网友
1楼 · 发布于 2024-06-12 01:39:13

unprocessed_urls = {...}创建一个新的set对象并将其分配给unprocessed_urls。这个新值在逻辑上与旧值相似的事实是不相关的;赋值给一个变量会覆盖以前在那里的任何内容。你知道吗

但是,可以从任何iterable创建collections.deque,因此您可以这样做

unprocessed_urls = deque(url for url in unprocessed_urls if ...)

创建一个新的collections.deque,以便分配给unprocessed_urls的所有值都具有相同的类型。你知道吗

相关问题 更多 >