完美解决爬虫时遇到的’NoneType’ object has no attribute ‘find’或’NoneType’ object has no attribute ‘find_all’问题

完美解决爬虫时遇到的’NoneType’ object has no attribute ‘find’或’NoneType’ object has no attribute ‘find_all’问题在网上看到了一个爬虫教程 就跟着学了起来 出现了点问题 NoneType objecthasnoa find 问题说明我是一个刚入门的小白 刚研究了点爬虫 我觉得这个问题其实就是没有找到相应的 htmlelement 网页元素 所以没有相应的元素方法 所以报错 noattribute 只要我们准确的找到相应的元素 就可以用 BeautifulSou 中的方

问题说明

data = body.find('div',attrs={'id':'7d'}) 

用属性标签attrs来寻找 id=7d 或class=c7d就可以了

怎么设置文件保存目录

文件目录我们可以自己设置保存位置,代码如下:

def write_data(data,name):
    file_name =name
    with open(file_name,'a',errors='ignore',newline='') as f:
        f_csv =csv.writer(f)
        f_csv.writerows(data)

if __name__ == '__main__':
    url = 'http://www.weather.com.cn/weather/101190401.shtml'
    html = get_content(url)
    result = get_data(html)
    write_data(result,'G:\weather.csv')  # 保存的位置我设置在了G盘根目录

爬取结果

爬去结果

完整代码

import requests
import time
import csv
import random
import socket
import http.client
import bs4
from bs4 import BeautifulSoup

def get_content(url,data = None):
    header = {
        'Accept':'image/webp,image/apng,image/*,*/*;q=0.8',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    }
    timeout = random.choice(range(80,180))
    while True:
        try:
            rep = requests.get(url,headers =header,timeout = timeout)
            rep.encoding= 'utf-8'
            break
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))

        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))

        except http.client.BadStatusLine as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))

        except http.client.IncompleteRead as e:
            print('6:', e)
            time.sleep(random.choice(range(5, 15)))
    return rep.text

def get_data(html_text):
    final=[]
    bs = BeautifulSoup(html_text,"html.parser")  # 创建BS对象
    body = bs.body
    data = body.find('div',attrs={'id':'7d'})
    # data = body.find('div',{'div':'7d'})
    print(type(data))
    ul = data.find('ul')
    li =ul.find_all('li')
    for day in li:
        temp = []
        date = day.find('h1').string
        temp.append(date)
        inf = day.find_all('p')
        temp.append(inf[0].string)
        if inf[1].find('span') is None:
            temperature_highest = None
        else:
            temperature_highest=inf[1].find('span').string
            temperature_highestm  =temperature_highest.replace("℃","")
        temperature_lowest = inf[1].find('i').string
        temperature_lowest = temperature_lowest.replace('℃','')
        temp.append(temperature_highest)
        temp.append(temperature_lowest)
        final.append(temp)
    return final

def write_data(data,name):
    file_name =name
    with open(file_name,'a',errors='ignore',newline='') as f:
        f_csv =csv.writer(f)
        f_csv.writerows(data)

if __name__ == '__main__':
    url = 'http://www.weather.com.cn/weather/101190401.shtml'
    html = get_content(url)
    result = get_data(html)
    write_data(result,'G:\weather.csv')

希望帮大家解决一定的问题。。。。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215694.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午1:39
下一篇 2026年3月18日 下午1:39


相关推荐

  • pycharm注释的快捷键_pycharm注释比较多怎么办

    pycharm注释的快捷键_pycharm注释比较多怎么办用鼠标选中需要注释的代码,三次按下:shift+‘即可快速注释

    2022年8月28日
    5
  • Linux Platform Device and Driver,platform_add_devices()->platform_driver_register()

    Linux Platform Device and Driver,platform_add_devices()->platform_driver_register()
    来自:http://www.diybl.com/course/6_system/linux/Linuxjs/200871/129585.html
    从Linux2.6起引入了一套新的驱动管理和注册机制:Platform_device和Platform_driver。
        Linux中大部分的设备驱动,都可以使用这套机制,设备用Platform_device表示,驱动用Platform_driver进行注册。
     
       

    2022年7月24日
    13
  • 微信支付申请退款步骤_微信怎么没有退款提示

    微信支付申请退款步骤_微信怎么没有退款提示本文是【浅析微信支付】系列文章的第八篇,主要讲解商户如何处理微信申请退款、退款回调、查询退款接口,其中有一些坑的地方,会着重强调。浅析微信支付系列已经更新七篇了哟~,没有看过的朋友们可以看一下哦。

    2022年8月1日
    18
  • 数据帧的学习整理

    数据帧的学习整理事先声明,本文档所有内容均在本人的学习和理解上整理,不具有权威性,甚至不具有准确性,本人也会在以后的学习中对不合理之处进行修改。在了解数据帧之前,我们得先知道OSI参考模型咱们从下往上数,数据帧在

    2022年8月5日
    8
  • 流处理旅程——storm之spout介绍

    流处理旅程——storm之spout介绍核心 Spout 中方法的说明 1 Spout 数据源消息源 Spout 是 storm 的 Topology 中的消息生产者 2 spout 介绍 2 1spout 的结构 Spout 是 storm 的核心组件之一 最源头的接口是 IComponent2 2Spout 发出的消息 Spout 从外部获取数据后 向 Topology 中发出的 Tuple 可以是可靠的 也可以是不可靠的 注意 一个可靠的消息源可以重新发射

    2026年3月17日
    1
  • clearfix的用法

    clearfix的用法如果有一个 DIV 作为外部容器 内部的 DIV 如果设置了 float 样式 则外部的容器 DIV 因为内部没有 clear 导致不能被撑开 看下面的例子 div 的布局如下 css 的写法如下 浏览器的显示如下 传统的解决方法如下 但是 这么多加一个 DIV 有点不妥 一是多了一个没有意义的 DIV 二是在用 dojo 做 Drag amp Drop 的时候 由于这个 DIV 是容器 DIV 的一个字

    2026年3月17日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号