君轶79 2022-08-15 15:47 采纳率: 100%
浏览 37
已结题

使用爬虫解析网页下载文件失败

问题遇到的现象和发生背景 、

在使用Python进行网络爬虫下载部分资源的时候,发现有些网的附件无法解析出ip地址。

附件在解析元素时,显示如下,

img

问题相关代码,请勿粘贴截图
    url = ‘http://www.ccgp.gov.cn/cggg/dfgg/qtgg/202207/t20220715_18271681.htm’
    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, 'lxml')
    main_info = soup.find('div', class_='vF_detail_content')
    att_info =   main_info.find_all('table')
    if not att_info:  # 没有附件,返回真
        return []
    att_file_list = []
    for tmp in att_info:
        detail_list = tmp.find_all('td')
        for detail in detail_list:
            if not detail:
                continue
            try:
                for con in detail.contents:
                    ip = con.attrs['href']
                    attach_file_name = con.text.strip()
                    if ip and attach_file_name:
                        att_file_list.append({'ip': ip, 'filename': attach_file_name})
                    else:
                        LogUtils.error(f"查找 ip:{ip}, file_name:{attach_file_name} 失败")
            except IndexError:
                continue
            except KeyError:
                continue
            except Exception as err:
                LogUtils.notset(f"{err}")
                continue
    return att_file_list
运行结果及报错内容

最终解析出的结果如下href为空,
<class 'dict'>: {'class': ['bizDownload'], 'href': '', 'id': 'E8D516E2245A268E4CFCF6190FB44A', 'title': '点击下载'}

我想要达到的结果

如何能够解析出正确的地址
href="//download.ccgp.gov.cn/oss/download?uuid=E8D516E2245A268E4CFCF6190FB44A"

  • 写回答

2条回答 默认 最新

  • honestman_ 2022-08-15 17:42
    关注

    可以在循环时候做一次判断:
    如果解析出的 href 为空,那么手动拼接一个 href = "//download.ccgp.gov.cn/oss/download?uuid=" + id
    如果不为空,那么 href 就是正确的地址

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月24日
  • 已采纳回答 8月16日
  • 修改了问题 8月15日
  • 修改了问题 8月15日
  • 展开全部

悬赏问题

  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?