【问题标题】:Encountering infinite recursion when using shelve module in Python在 Python 中使用搁置模块时遇到无限递归
【发布时间】: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 中对其进行分析。

【问题讨论】:

  • 看起来BeautifulSoup NavigableString 对象不太适合搁置。尝试改用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


【解决方案1】:

这是一个knownissue,里面有泡菜和BeautifulSoup。我怀疑搁置的问题是相关的。

【讨论】:

  • 但是我将传递的任何数据转换为字符串,所以不应该避免这个问题,还是因为我已经加载了 BeautifulSoup 而成为问题?稍后我会尝试弄乱字符串值的格式,但这真的很令人沮丧。另外,您对数据存储模块/库还有其他建议吗?
  • 没关系,我忘了将一些值转换为文本。现在它正在工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-20
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多