【发布时间】:2013-10-17 17:42:47
【问题描述】:
我正在使用 Python 中的 Mechanize 和 BeautifulSoup4 编写一个网络爬虫。为了存储它收集的数据以供进一步分析,我使用了搁置模块。出现问题的代码块在这里。
url_dict=shelve.open("url_dict.dat")
html=r.read()
soup=BeautifulSoup(html)
frames=soup.find_all("a",{"class":br_class})#br_class is defined globally
time.sleep(1)
for item in frames:
url_suffix=item['href']
full_url=url_prefix+url_suffix
full_url=full_url.encode('ascii','ignore')
if str(full_url) not in url_dict:
url_dict[str(full_url)]=get_information(full_url,sr)
time.sleep(1)
但是,此代码在遇到错误之前确实会经历一个循环。函数get_information() 开头如下:
def get_information(full_url,sr):
information_set=dict()
r=sr.open(full_url)
information_set['url']=full_url
print("Set url")
html=r.read()
soup=BeautifulSoup(html)
information_set["address"]=soup.find("h1",{"class":"prop-addr"}).text
sr 是一个读取 url 的浏览器对象,而 url_suffix 是一个 unicode 字符串。 get_information() 返回的对象是一个字典对象。所以 url_dict 是字典的字典。
在此代码的第二个循环中,我遇到以下错误:
Traceback (most recent call last):
File "collect_re_data.py", line 219, in <module>
main()
File "collect_re_data.py", line 21, in main
data=get_html_data()
File "collect_re_data.py", line 50, in get_html_data
url_dict[str(full_url)]=get_information(full_url,sr)
File "C:\Python27\lib\shelve.py", line 132, in __setitem__
p.dump(value)
File "C:\Python27\lib\copy_reg.py", line 74, in _reduce_ex
getstate = self.__getstate__
RuntimeError: maximum recursion depth exceeded while calling a Python object
另外,有没有更好的方法来处理这样的数据存储?我的最终目标是将所有数据传输到 .csvfile 中,以便我可以在 R 中对其进行分析。
【问题讨论】:
-
看起来
BeautifulSoupNavigableString对象不太适合搁置。尝试改用unicode(soup.find("h1",{"class":"prop-addr"}).text)。 -
另外,
get_information()似乎没有返回任何东西。您确定您没有遗漏return information_set或该功能中的其他内容吗? -
get_information返回的内容是否可能包含(直接或间接)本身(或包含url_dict)?同时,由于shelve只使用pickle.dumps(value),如果您将其剥离为“构建价值,然后腌制它”,这可能更容易调试。
标签: python dictionary runtime-error infinite-loop shelve