python爬虫程序有问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python爬虫程序有问题相关的知识,希望对你有一定的参考价值。
代码如下 问题应该出在gethtml(url)函数,gethtml(url)的返回值是<function gethtml at 0x0000000003476F98>。请问应该怎么修改?
import re
import urllib
def gethtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getpicture(html):
reg = r'src=(.*?\.jpg)'
picturere = re.compile(reg)
picturelist = re.findall(picturere,html)
x=0
for pictureurl in picturelist:
urllib.urlretrieve(pictureurl,'%s.jpg' %x)
x+=1
url = raw_input("url:")
增加一句
html = gethtml(url)
这样修改之后,能运行一段时间,然后会报错:
File "F:\Program Files (x86)\python\Lib\urllib.py", line 477, in open_local_file
raise IOError(e.errno, e.strerror, e.filename)
标注的代码为:
raise IOError(e.errno, e.strerror, e.filename)
这是为什么呢?
IOError就说明你抓取的URL连接失效,在getpicture里加一个try except,无法打开链接时,
没有办法,继续执行下一个Url
import systry:
urllib.urlretrieve(pictureurl,'%s.jpg' %x)
except:
print "Unexpected error:", sys.exc_info()[0]追问
我改成这样了,的确能检测到失效链接,但是还是会报错


放的位置不对。。。
你错误的地方是urllib.urlretrieve(pictureurl,'%s.jpg' %x)
所以把这一行改为
try:urllib.urlretrieve(pictureurl,'%s.jpg' %x)
except:
print "Unexpected error:", sys.exc_info()[0] 参考技术A 帮你慢慢看~~~追问
我在想会不会是那个图片文件的连接失效了,才会出错。
以上是关于python爬虫程序有问题的主要内容,如果未能解决你的问题,请参考以下文章