簡體   English   中英

使用BeautifulSoup時出現“ NoneType”錯誤

[英]`NoneType`-error when using BeautifulSoup

下面是我的代碼...

from bs4 import BeautifulSoup

import requests


for count in range(1,2):


    r = requests.get('http://manufacturer.indiatradepage.com/all/a_a_enterprises/' + str(count) + '/',headers={'User-Agent': 'Googlebot'})

    soup = BeautifulSoup(r.text,'lxml')

    data = soup.find('div',class_='container_main')

    for links in data.find_all('div',class_='com_countainer'):
        for link in links.find_all('a')[0:1]:
            l = link['href']
            r = requests.get(l)
            soup = BeautifulSoup(r.text,'lxml')

            data = soup.find('td',{"id":"intro_txt"})
            table1 = data.find('table',{"style":"max-height: 400px !important"})

            body1 = table1.find('div',class_='f_body')


            table2 = data.find('div',{"id":"f3_1"})

            div = table2.find('div',class_='f_body')


            body2 = div.find('div',{"style":"text-transform:capitalize; "})

            print body2.text + body1.text

我得到這個下面的錯誤。

追溯(最近一次通話):文件“ C:/Python27/indiatradepage_try.py”,第19行,在body1 = table1.find('div',class _ ='f_body')AttributeError:'NoneType'對象沒有屬性'找'

由於以下錯誤,我的代碼每次都被破壞。

您可以通過不嘗試在NoneType對象上使用屬性.find解決此問題,這就是您在body1 = table1.find('div',class_='f_body')以及在table2 = data.find('div',{"id":"f3_1"})上嘗試執行的操作table2 = data.find('div',{"id":"f3_1"})

您可以執行類似的操作,這將檢查表是否為None,如果不是,則打印.find而不是.find ,然后繼續循環。

from bs4 import BeautifulSoup

import requests


for count in range(1,2):

    r = requests.get('http://manufacturer.indiatradepage.com/all/a_a_enterprises/' + str(count) + '/',headers={'User-Agent': 'Googlebot'})

    soup = BeautifulSoup(r.text,'lxml')

    data = soup.find('div',class_='container_main')

    for links in data.find_all('div',class_='com_countainer'):
        for link in links.find_all('a')[0:1]:
            l = link['href']
            r = requests.get(l)
            soup = BeautifulSoup(r.text,'lxml')

            data = soup.find('td',{"id":"intro_txt"})
            table1 = data.find('table',{"style":"max-height: 400px !important"})

            if table1 != None:
                body1 = table1.find('div',class_='f_body').text
            else:
                body1 = ' table1 no present '


            table2 = data.find('div',{"id":"f3_1"})
            if table2 != None:
                div = table2.find('div',class_='f_body')
                body2 = div.find('div',{"style":"text-transform:capitalize; "}).text
            else:
                body2 = ' table2 not present '

            print (body2 + body1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM