找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 4234|回复: 1

[求助] 一个简单的多线程python抓取网页信息程序

1

主题

2

帖子

7

积分

贫民

积分
7
ludalong 发表于 2016-5-24 09:23:11 | 显示全部楼层 |阅读模式
一个简单的多线程python抓取网页信息程序中出现list溢出提示,具体代码和错误提示在下面有描述,望高手们解惑,非常感谢


错误日志:
代码每次运行到spider函数内的content=each.xpath()这个地方的时候就报错:
  1. Traceback (most recent call last):
  2. File "E:/data/C++/Python/����ѧԺ/XPath-and-multithreading-crawler_v1/Դ��/tiebaspider.py", line 50, in <module>
  3. results = pool.map(spider, page)
  4. File "E:\data\C++\Python\python2.7.9\lib\multiprocessing\pool.py", line 251, in map
  5. return self.map_async(func, iterable, chunksize).get()
  6. File "E:\data\C++\Python\python2.7.9\lib\multiprocessing\pool.py", line 558, in get
  7. raise self._value
  8. IndexError: list index out of range
复制代码




以下为源代码
  1. #-*-coding:utf8-*-

  2. from lxml import etree
  3. from multiprocessing.dummy import Pool as ThreadPool
  4. import requests
  5. import json
  6. import sys
  7. reload(sys)


  8. sys.setdefaultencoding('utf-8')
  9. '''重新运行之前请删除content.txt,因为文件操作使用追加方式,会导致内容太多。'''


  10. def towrite(contentdict):
  11.     f.writelines(u'回帖时间:' + str(contentdict['topic_reply_time']) + '\n')
  12.     f.writelines(u'回帖内容:' + unicode(contentdict['topic_reply_content']) + '\n')
  13.     f.writelines(u'回帖人:' + contentdict['user_name'] + '\n\n')


  14. def spider(url):
  15.     html = requests.get(url)
  16.     selector = etree.HTML(html.text)
  17.     print selector
  18.     content_field = selector.xpath('//div[@class="l_post j_l_post l_post_bright  "]')
  19.     item = {}
  20.     for each in content_field:
  21.         reply_info = json.loads(each.xpath('@data-field')[0].replace('"', ''))
  22.         author = reply_info['author']['user_name']
  23.         reply_time = reply_info['content']['date']
  24.         content = each.xpath('div[@class="d_post_content_main"]/div/cc/\
  25.         div[@class="d_post_content j_d_post_content"]/text()')[0]
  26.         print (content)
  27.         print (reply_time)
  28.         print (author)
  29.         item['user_name'] = author
  30.         item['topic_reply_content'] = content
  31.         item['topic_reply_time'] = reply_time
  32.         towrite(item)

  33. if __name__ == '__main__':
  34.     pool = ThreadPool(2)
  35.     f = open('content.txt', 'a')
  36.     page = []
  37.     for i in range(1, 21):
  38.         newpage = 'http://tieba.baidu.com/p/3522395718?pn=' + str(i)
  39.         page.append(newpage)

  40.     results = pool.map(spider, page)
  41.     pool.close()
  42.     pool.join()
  43.     f.close()
复制代码


回复

使用道具 举报

1

主题

2

帖子

7

积分

贫民

积分
7
ludalong  楼主| 发表于 2016-5-24 10:00:10 | 显示全部楼层
有大神在吗,麻烦帮忙看看啊,非常感谢
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表