首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将"catch-all“异常子句应用于复杂的python web抓取脚本?

如何将"catch-all“异常子句应用于复杂的python web抓取脚本?
EN

Stack Overflow用户
提问于 2009-10-05 22:53:39
回答 2查看 647关注 0票数 0

我有一个CSV格式的100个网站的列表。所有的站点都有相同的通用格式,包括一个包含7列的大表。我写了这个脚本,从每个网站的第7列提取数据,然后将这些数据写入文件。然而,下面的脚本部分工作:打开输出文件(在运行脚本之后)显示跳过了一些东西,因为它只显示了98次写入(显然,该脚本还注册了许多异常)。关于如何在此上下文中实现“捕获异常”的指导将不胜感激。谢谢!

代码语言:javascript
复制
import csv, urllib2, re
def replace(variab): return variab.replace(",", " ")

urls = csv.reader(open('input100.txt', 'rb'))  #access list of 100 URLs
for url in urls:
    html = urllib2.urlopen(url[0]).read()  #get HTML starting with the first URL
    col7 = re.findall('td7.*?td', html)  #use regex to get data from column 7
    string = str(col7)  #stringify data
    neat = re.findall('div3.*?div', string)  #use regex to get target text  
    result = map(replace, neat)  #apply function to remove','s from elements
    string2 = ", ".join(result)  #separate list elements with ', ' for export to csv
    output = open('output.csv', 'ab') #open file for writing 
    output.write(string2 + '\n') #append output to file and create new line
    output.close()

返回:

代码语言:javascript
复制
Traceback (most recent call last):
 File "C:\Python26\supertest3.py", line 6, in <module>
  html = urllib2.urlopen(url[0]).read()
 File "C:\Python26\lib\urllib2.py", line 124, in urlopen
  return _opener.open(url, data, timeout)
 File "C:\Python26\lib\urllib2.py", line 383, in open
  response = self._open(req, data)
 File "C:\Python26\lib\urllib2.py", line 401, in _open
  '_open', req)
 File "C:\Python26\lib\urllib2.py", line 361, in _call_chain
  result = func(*args)
 File "C:\Python26\lib\urllib2.py", line 1130, in http_open
  return self.do_open(httplib.HTTPConnection, req)
 File "C:\Python26\lib\urllib2.py", line 1103, in do_open
  r = h.getresponse()
 File "C:\Python26\lib\httplib.py", line 950, in getresponse
  response.begin()
 File "C:\Python26\lib\httplib.py", line 390, in begin
  version, status, reason = self._read_status()
 File "C:\Python26\lib\httplib.py", line 354, in _read_status
  raise BadStatusLine(line)
BadStatusLine
>>>>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-10-05 23:19:37

for循环的主体放入:

代码语言:javascript
复制
for url in urls:
  try:
    ...the body you have now...
  except Exception, e:
    print>>sys.stderr, "Url %r not processed: error (%s) % (url, e)

(或者,使用logging.error而不是愚蠢的print>>,如果您已经在使用标准库的logging模块,并且应该使用;-))。

票数 2
EN

Stack Overflow用户

发布于 2009-10-05 22:58:21

我建议您阅读Python文档,特别是第8.3节--处理异常。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1522823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档