如何将“catchall”异常子句应用于复杂的python webscraping脚本?

2024-04-19 18:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有100个CSV格式的网站列表。所有站点都有相同的通用格式,包括一个有7列的大表。我编写了这个脚本,从每个网站的第7栏中提取数据,然后将这些数据写入文件。但是,下面的脚本部分起作用:打开输出文件(在运行脚本之后)会显示某些内容被跳过,因为它只显示98次写入(显然,脚本还注册了一些异常)。对于如何在这种情况下实施“捕捉异常”的指导将不胜感激。谢谢您!在

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()

返回:

^{pr2}$

Tags: 文件csvto数据re脚本foroutput
2条回答

使for循环的主体变成:

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模块,请使用logging.error而不是goofyprint>>,如果您已经在使用标准库的logging模块,您应该;-)])。在

我建议阅读Errors and ExceptionsPython文档,特别是第8.3节处理异常。在

相关问题 更多 >