我正在用BeautifulSoup做一个文本爬虫。但是当我运行这段代码时,我得到的错误代码是
Traceback (most recent call last):
File "D:\Python27\Crawling.py", line 33, in <module>
text = content.get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'
如果你能告诉我如何修复它,我将不胜感激。
import urllib
from bs4 import BeautifulSoup
import xml.dom.minidom
keyWord = raw_input("Enter the key-word : ")
#Enter my Search KeyWord
address = "http://openapi.naver.com/search?key=8d4b5b7fef7a607863013302754262a3&query=" + keyWord + "&display=5&start=1&target=kin&sort=sim"
search_result = urllib.urlopen(address)
raw_data = search_result.read()
parsed_result = xml.dom.minidom.parseString(raw_data)
links = parsed_result.getElementsByTagName('link')
source_URL = links[3].firstChild.nodeValue
#The number 3 has no meaning, it has 0 to 9 and I just chose 3
page = urllib.urlopen(source_URL).read()
#save as html file
g = open(keyWord + '.html', 'w')
g.write(page)
g.close()
#open html file
g = open(keyWord + '.html', 'r')
bs = BeautifulSoup(g)
g.close()
content = bs.find(id="end_content")
text = content.get_text()
#save as text file
h = codecs.open(keyWord + '.txt', 'w', 'utf-8')
h.write(keyWord + ' ')
h.write(text)
print "file created"
发布于 2014-03-31 22:11:33
考虑到@Hooked和@alecxe的答案,使用requests
的方法如下所示。注意,我将对搜索查询使用handbag
关键字。
import requests as rq
from bs4 import BeautifulSoup as bsoup
from xml.dom.minidom import parseString
url = "http://openapi.naver.com/search?key=8d4b5b7fef7a607863013302754262a3&query=handbag&display=100&start=1&target=kin&sort=sim"
result = rq.get(url)
parsed_result = parseString(result.content)
links = parsed_result.getElementsByTagName("link")
new_url = links[3].firstChild.nodeValue
new_result = rq.get(new_url).content
g = open("handbag.html", "w")
g.write(new_result)
g.close()
g = open("handbag.html", "r")
soup = bsoup(g)
g.close()
content = soup.find("div", class_="end_content")
text = content.get_text()
print text.encode("utf-8").strip()
.encode("utf-8")
部分用于处理朝鲜语字符的输出。结果如下:
아디다스 그래픽핸드백
거의품절이던데............
어디파는데알수없을가요 ㅜ ㅜ ??!?!?
[Finished in 4.7s]
如果这有帮助,请让我们知道。
发布于 2014-03-31 21:52:50
这个错误提示你解决了这个问题。令人不快的一句话来自:
content = bs.find(id="end_content")
它是从你的soup触发的,所以bs
没有带id="end_content"
的元素。当BeautifulSoup找不到元素时,它不会抛出错误,而只是返回None
。检查您的源html,并仔细检查id是否正确。
顺便说一句,也许有必要研究一下模块requests
来处理url解析。它比像您这样简单地连接字符串要健壮得多。
发布于 2014-03-31 21:55:34
问题是,虽然有一个带有class="end_content"
的div,但是id="end_content"
中没有元素。
替换:
content = bs.find(id="end_content")
with (注意,这里需要使用class_
,因为class
在python中是一个保留关键字):
content = bs.find("div", class_="end_content")
或者,或者:
content = bs.find("div", {"class": "end_content"})
此外,请注意,出于性能和显式原因,最好在此处指定div
标记,因为您知道它将是一个div
。
https://stackoverflow.com/questions/22763236
复制相似问题