python - 如何避免 python 蜘蛛程序中出现重复的下载网址?

标签 python web-crawler

我用python写了一个蜘蛛程序。它可以递归地抓取网页。我想避免下载相同的页面,因此我将网址存储在列表中,如下所示:

urls = []
def download(mainPage):  # mainPage is a link
    global urls
    links = getHrefLinks(mainPage)
    for l in links:
        if l not in urls:
            urls.append(l)
            downPage(l)

但是有一个问题,当链接过多时,url会很大,代码if l not in urls效率较低。如何解决问题?避免重复下载网址而又不占用太多内存并提高效率的最佳方法是什么?

最佳答案

您可以将网址设置为 set :

urls = set()
def download(mainPage):  # mainPage is a link
    global urls
    links = getHrefLinks(mainPage)
    for l in links:
        if l not in urls:
            urls.add(l) #instead of append
            downPage(l)

对象的查找,即 x in s 位于 average case 中,复杂度为 O(1),这比 list 的平均情况要好。

关于python - 如何避免 python 蜘蛛程序中出现重复的下载网址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26771396/

相关文章:

python - 如何创建用于在 python 中设置对象属性的模板函数?

python - 为包含 : join table on itself with selecting all column of 1st table and some column of right table 的 sql 查询制作等效的 pandas 数据框

python - Scrapy Crawler 不跟踪链接

web-scraping - scrapy-如何停止重定向(302)

javascript - 如何获取 casper.js http.status 代码?

python - 了解如何在 pygame 中更新屏幕?

python - 从映射列表中提取唯一项

python - 如何从文本文件中的特定行获取计时并用Python中的另一行减去它?

ajax - 为什么像 twitter、gawker 这样的网站使用 #!而不是简单的网址?

python - Python 中的网络爬虫