在網上看到了一個爬蟲教程,就跟着學了起來,出現了點問題:‘NoneType’ object has no attribute ‘find’;
問題說明
我是一個剛入門的小白,剛研究了點爬蟲,我覺得這個問題其實就是沒有找到相應的html element(網頁元素),所以沒有相應的元素方法,所以報錯“no attribute”。
只要我們準確的找到相應的元素,就可以用BeautifulSoup中的方法進行解析了。
下圖是問題出現的地方:
打印出來的type(data)爲nonetype,所以就是沒有找到元素。於是我們可以使用另一種尋找元素的方法
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')
希望幫大家解決一定的問題。。。。