2017-10-21 104 views
0

我正在計數google主頁上的單詞。但是我在初始階段得到了AttributeError。Python-AttributeError:'NoneType'對象沒有屬性'lower'

我的代碼 - >

import requests 
from bs4 import BeautifulSoup 
import operator 

def main(url): 
    word_list=[] 
    source_code=requests.get(url).text 
    soup=BeautifulSoup(source_code,'lxml') 
    for post_text in soup.findAll('a'): 
     content=post_text.string 
     words=content.lower().split() 
     for each_word in words: 
      print(each_word) 
      word_list.append(each_word) 

main('https://www.google.co.in/?gfe_rd=cr&dcr=0&ei=2-nqWavnB4WN8Qf4n7eQAw') 

我的輸出是 - >

images 
maps 
play 
youtube 
news 
gmail 
drive 
Traceback (most recent call last): 
    File "word_freq.py", line 18, in <module> 
    main('https://www.google.co.in/?gfe_rd=cr&dcr=0&ei=2-nqWavnB4WN8Qf4n7eQAw') 
    File "word_freq.py", line 13, in main 
    words=content.lower().split() 
AttributeError: 'NoneType' object has no attribute 'lower' 
+0

您需要添加一個'如果內容後'含量= POST_TEXT不None'。字符串「,因爲所有'a'標籤都不需要文本字符串。 – ZdaR

回答

0
  1. 您解析在HTML網頁,所以你需要

    湯= BeautifulSoup(source_code,'html.parser')

  2. 字符串是不正確的屬性得到任何標籤的內容,用文字:

    含量= post_text.text