Skip to main content
 首页 » 编程设计

python之无法使用 set 剔除重复结果

2025年05月04日23powertoolsteam

我用 python 编写了一个脚本来抓取标题为 England 的表格下的所有链接,然后当我的脚本到达内页时使用这些链接,然后它将抓取下一页链接.我知道如果我修复脚本中使用的 xpath,我可能会获得唯一的下一页 url。

但是,这里的主要目标是确定为什么我的脚本在使用 set() 时仍会生成重复项。

我的脚本:

import requests 
from lxml.html import fromstring 
from urllib.parse import urljoin 
 
link = "http://tennishub.co.uk/" 
 
processed_links = set() 
processed_nextpage_links = set() 
 
def get_links(url): 
    response = requests.get(url) 
    tree = fromstring(response.text) 
 
    unprocessed_links = [urljoin(link,item.xpath('.//a/@href')[0]) for item in tree.xpath('//*[@class="countylist"]')] 
    for nlink in unprocessed_links: 
        if nlink not in processed_links: 
            processed_links.add(nlink) 
    get_nextpage_links(processed_links) 
 
def get_nextpage_links(itemlinks): 
    for ilink in itemlinks: 
        response = requests.get(ilink) 
        tree = fromstring(response.text) 
        titles = [title.xpath('.//a/@href')[0] for title in tree.xpath('//div[@class="pagination"]') if title.xpath('.//a/@href')] 
        for ititle in titles: 
            if ititle not in processed_nextpage_links: 
                processed_nextpage_links.add(ititle) 
 
        for rlink in processed_nextpage_links: 
            print(rlink) 
 
if __name__ == '__main__': 
    get_links(link) 

我得到的结果是这样的:

/tennis-clubs-by-county/Durham/2 
/tennis-clubs-by-county/Durham/2 
/tennis-clubs-by-county/Durham/2 
/tennis-clubs-by-county/Cheshire/2 
/tennis-clubs-by-county/Derbyshire/2 
/tennis-clubs-by-county/Durham/2 
/tennis-clubs-by-county/Cheshire/2 
/tennis-clubs-by-county/Derbyshire/2 
/tennis-clubs-by-county/Durham/2 

请您参考如下方法:

每次调用 get_nextpage_links 时,您都会打印到目前为止收集的所有链接。

我猜你会想要完全删除 print ,并在完成后打印列表,最好在任何 def 之外(使你的函数可重用,并且将任何外部副作用推迟到调用代码)。

一个没有全局变量的更好的解决方案可能是让 get_links 收集一个集合并返回它,在您调用它时将对该集合的引用传递给 get_nextpage_links,并且 (显然)添加任何新链接。

因为您使用的是集合,所以在添加链接之前没有特别需要检查链接是否已经在集合中。无法向该数据类型添加重复项。