对于一个班级,我有一个练习,我需要计算任何给定网页上的图片数量。我知道每张图片都以图片开头,因此我正在使用正则表达式来尝试找到它们。不过,我不断收到一个计数我知道是错的,什么是错我的代码:使用urllib来计算网页上图片的数量
import urllib
import urllib.request
import re
img_pat = re.compile('<img.*>',re.I)
def get_img_cnt(url):
try:
w = urllib.request.urlopen(url)
except IOError:
sys.stderr.write("Couldn't connect to %s " % url)
sys.exit(1)
contents = str(w.read())
img_num = len(img_pat.findall(contents))
return (img_num)
print (get_img_cnt('http://www.americascup.com/en/schedules/races'))
感谢,做的工作,我不要。 '不明白'正在做什么?' – kflaw
它告诉正则表达式在第一个'>'遇到的时候停止搜索,而不是最新的。所以它会捕获每个''而不只是一个大的''包含其他
The '?' tells the regular expression to match the arbitrary '.*' pattern with as _few_ characters as possible, rather than as _many_ (which is the default). So if we personify regex a bit longer, it would see ''尽快可能结束那场比赛。 –