使用urllib计算网页上的图像数量

kfl*_*law 3 html python regex urllib html-parsing

对于一个课程,我有一个练习,我需要计算任何给予网页上的图像数量.我知道每个图像都以,所以我使用正则表达式尝试找到它们.但我不断得到一个我知道错误,我的代码有什么问题:

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'))
Run Code Online (Sandbox Code Playgroud)

ale*_*cxe 9

不要使用正则表达式来解析HTML,使用html解析器,如lxmlBeautifulSoup.这是一个工作示例,如何img使用BeautifulSoup请求获取标记计数:

from bs4 import BeautifulSoup
import requests


def get_img_cnt(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content)

    return len(soup.find_all('img'))


print(get_img_cnt('http://www.americascup.com/en/schedules/races'))
Run Code Online (Sandbox Code Playgroud)

这是一个使用lxml和的工作示例requests:

from lxml import etree
import requests


def get_img_cnt(url):
    response = requests.get(url)
    parser = etree.HTMLParser()
    root = etree.fromstring(response.content, parser=parser)

    return int(root.xpath('count(//img)'))


print(get_img_cnt('http://www.americascup.com/en/schedules/races'))
Run Code Online (Sandbox Code Playgroud)

两个片段都打印出来106.

另见:

希望有所帮助.