Я пытаюсь очистить информацию от Википедии, используя приведенную ниже функцию, но я столкнулся с Ошибка атрибута, потому что возвращается вызов функции Нет. Может ли кто-нибудь попробовать и объяснить, почему это возвращается? Нет?Почему это возвращает NoneType?
import wikipedia as wp
import string
def add_section_info(search):
HTML = wp.page(search).html().encode("UTF-8") #gets HTML source from Wikipedia
with open("temp.xml",'w') as t: #write HTML to xml format
t.write(HTML)
table_of_contents = []
dict_of_section_info = {}
#This extracts the info in the table of contents
with open("temp.xml",'r') as r:
for line in r:
if "toclevel" in line:
new_string = line.partition("#")[2]
content_title = new_string.partition("\"")[0]
tbl = string.maketrans("_"," ")
content_title = content_title.translate(tbl)
table_of_contents.append(content_title)
print wp.page(search).section("Aortic rupture") #this is None, but shouldn't be
for item in table_of_contents:
section = wp.page(search).section(item).encode("UTF-8")
print section
if section == "":
continue
else:
dict_of_section_info[item] = section
with open("Section_Info.txt",'a') as sect:
sect.write(search)
sect.write("------------------------------------------\n")
for item in dict_of_section_info:
sect.write(item)
sect.write("\n\n")
sect.write(dict_of_section_info[item])
sect.write("####################################\n\n")
add_section_info("Abdominal aortic aneurysm")
То, что я не понимаю, что если я бегу add_section_info("HIV")
, к примеру, она прекрасно работает.
Исходный код для импортированной Википедию here
Мой выход на приведенный выше код следующим образом:
Abdominal aortic aneurysm
Signs and symptoms
Traceback (most recent call last):
File "/home/pharoslabsllc/Documents/wikitest.py", line 79, in <module>
add_section_info(line)
File "/home/pharoslabsllc/Documents/wikitest.py", line 30, in add_section_info
section = wp.page(search).section(item).encode("UTF-8")
AttributeError: 'NoneType' object has no attribute 'encode'
Можете ли вы сказать нам, где происходит эта ошибка? Просто добавьте трассировку к вопросу. – TigerhawkT3
Попробуйте 'print (repr (item))' внутри цикла, который терпит неудачу. – Bakuriu
У вас есть значение, жестко закодированное там. Что произойдет, если вместо 'print wp.page (search) .section (" Aortic rupture ")' you did 'print wp.page (search) .section (item)'? – Makoto