[英]`NoneType`-error when using BeautifulSoup
Below is my code... 下面是我的代码...
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
im getting this below error. 我得到这个下面的错误。
Traceback (most recent call last): File "C:/Python27/indiatradepage_try.py", line 19, in body1 = table1.find('div',class_='f_body') AttributeError: 'NoneType' object has no attribute 'find' 追溯(最近一次通话):文件“ C:/Python27/indiatradepage_try.py”,第19行,在body1 = table1.find('div',class _ ='f_body')AttributeError:'NoneType'对象没有属性'找'
due to below error, my code is breaking everytime. 由于以下错误,我的代码每次都被破坏。
You can handle that by not trying to use attribute .find
on a NoneType object, which is what you are trying to do at body1 = table1.find('div',class_='f_body')
, and also probably at table2 = data.find('div',{"id":"f3_1"})
您可以通过不尝试在NoneType对象上使用属性.find
解决此问题,这就是您在body1 = table1.find('div',class_='f_body')
以及在table2 = data.find('div',{"id":"f3_1"})
上尝试执行的操作table2 = data.find('div',{"id":"f3_1"})
You can do something like this, that will check if the table is None, and if it is, instead of .find
, print out that it's not there and then continue looping. 您可以执行类似的操作,这将检查表是否为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.