You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无BeautifulSoup的Python2.7本地爬虫:重复结果与匹配失败问题

解决你的Python 2.7本地HTML爬虫问题

我来帮你逐一分析并解决这两个棘手的问题:

问题1:脚本执行后出现重复结果

问题根源

你的ex_link函数里嵌套了不必要的双层循环,直接导致每个链接被重复添加多次。看这段代码:

for element in result:
    for i in range(len(result)):
        raw = result[result.index(element)].replace(" ","")
        # ... 后续添加链接的逻辑

外层循环遍历所有匹配到的<h2>元素,内层循环又把整个result列表遍历一遍——相当于每个链接会被处理len(result)次。比如result里有3个<h2>元素,每个链接就会被添加3次,最终出现大量重复。

修复代码

去掉多余的内层循环,直接遍历每个<h2>元素处理即可,同时把links移到函数内部避免全局变量累积:

def ex_link(y):
    result = []
    for i in y:
        if i is not None and i.find("<h2>") != -1:
            result.append(i)
    links = []
    for element in result:
        raw = element.replace(" ","")
        first = raw.find("<ahref")
        end = raw.find(".html")
        # 增加判断避免找不到标签时报错
        if first != -1 and end != -1:
            extracted_link = raw[first+7:end+6]
            # 提前去掉链接两端的引号,为后续匹配做准备
            extracted_link = extracted_link.strip('"')
            links.append(extracted_link)
    print(links)
    return links

问题2:链接字符串比较全部返回false

问题根源

  1. 引号不一致:你提取的链接自带双引号(比如"file:///home/godzilla/crawler-project/test-2.html"),但待匹配的测试链接里大部分没有引号,直接做严格字符串对比肯定不相等。
  2. 链接本身不匹配:待匹配列表里的test-4.htm少了最后一个l,和你提取的test-4.html格式不一致;另外http://www.google.com和test-1.html本身就不在你爬取的结果里。

修复方案

  1. 提取链接时去掉两端引号(上面的修复代码已经加入extracted_link.strip('"')实现)。
  2. 匹配时可以用"成员判断"替代逐个严格对比,同时处理格式差异:
# 先获取清洗后的提取链接列表
clean_links = ex_link(link_test)
# 整理待匹配的测试链接为标准格式
target_links = [
    "file:///home/godzilla/crawler-project/test-2.html",
    "file:///home/godzilla/crawler-project/test-3.html",
    "file:///home/godzilla/crawler-project/test-4.htm",
    "http://www.google.com",
    "file:///home/godzilla/crawler-project/test-1.html"
]

# 处理.htm和.html的差异,统一转为.html格式
standard_targets = [link.replace(".htm", ".html") for link in target_links]

for link in clean_links:
    if link in standard_targets:
        print(f"{link} found!")
    else:
        print(f"{link} not found!")

额外优化建议

  • 手动解析HTML容易受标签格式影响(比如换行、空格差异),可以用正则表达式更可靠地提取链接:
import re
# 在ex_link函数里替换为正则提取
pattern = re.compile(r'<a href="(file://.*?\.html)"')
for element in result:
    matches = pattern.findall(element)
    links.extend(matches)

这样能精准抓取href属性里的链接,不用手动处理字符串截取。

内容的提问来源于stack exchange,提问作者Godzilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:41:22