return BeautifulSoup AttributeError:'NoneType'对象没有属性'encode'

时间:2018-11-18 23:55:50

标签: python exception beautifulsoup attributeerror

晚安,为什么我返回“美元”,却要返回“ BeautifulSoup AttributeError:'NoneType'对象没有属性'encode'”,我在做什么错呢?我想在这段代码中加上美元报价

import
from bs4 import BeautifulSoup
import urllib.request as url

 site = "https://economia.uol.com.br/cotacoes/"
       try:
           url2 = site
           con = url.urlopen(url2, None, 7) 

           if con.status == 200:
               HTML = con.read() 

               soup = BeautifulSoup(HTML, 'html.parser')  

               dolar = re.search(r'Cotacao do Dolar: ',
                                       str(soup.find('div', attrs={'class': 'subtituloGrafico subtituloGraficoValor'})))  
               return dolar

       except Exception as e:

           if str(e) == 'HTTP Error 404: NOT FOUND':
               return 'Error'

           return str(e)

2 个答案:

答案 0 :(得分:1)

正如@Pythonista所说,因为汤中什么也没找到。我尝试在浏览器中按类搜索您需要的内容,然后发现class="subtituloGrafico subtituloGraficoValor"属于<a>。因此,我了解您可能想要得到的东西。

注意:soup.find("h3",{"class":"tituloGrafico"})用于缩小搜索范围

from bs4 import BeautifulSoup
import urllib.request as url
import re

site = "https://economia.uol.com.br/cotacoes/"
def func(site=site):
        try:
            url2 = site
            con = url.urlopen(url2, None, 7) 
            if con.status == 200:
                HTML = con.read() 
                soup = BeautifulSoup(HTML, 'lxml')
                sub = soup.find("h3",{"class":"tituloGrafico"})
                title = sub.findChild("a").text
                dolar = sub.find('a', attrs={'class': "subtituloGrafico subtituloGraficoValor"}).text
                print(title,dolar)
                #dolar = re.search(r'Cotacao do Dolar:(.*?)',text)
                return dolar
        except Exception as e:
            raise e
            if str(e) == 'HTTP Error 404: NOT FOUND':
                return 'Error'
            return str(e)
func()

答案 1 :(得分:0)

简单。这个:

soup.find('div', attrs={'class': 'subtituloGrafico subtituloGraficoValor'})

返回None,因为在汤中什么也没找到。确保您实际上在正确搜索它,它不是动态创建的。

您也可以按文本搜索并使用BS提取它,而无需显式使用re。