【问题标题】:BeautifulSoup: Extract img alt dataBeautifulSoup:提取 img alt 数据
【发布时间】:2012-07-27 23:07:32
【问题描述】:

我有以下图像 html,我正在尝试解析 alt 中的信息。目前我能够成功提取图像。

html(我目前解析的内容

<img class="rslp-p" alt="Sony Cyber-shot DSC-W570 16.1 MP Digital Camera - Silver" src="http://i.ebayimg.com/00/$(KGrHqZ,!j!E5dyh0jTpBO(3yE7Wg!~~_26.JPG?set_id=89040003C1" itemprop="image" />

我根据我解析的内容构造图像名称:

当前代码

def main(url, output_folder="~/images"):
         """Download the images at url"""
         soup = bs(urlopen(url))
         parsed = list(urlparse.urlparse(url))
         count = 0
         for image in soup.findAll("img"):
             print image
             count += 1
             print count
             print "Image: %(src)s" % image
             image_url = urlparse.urljoin(url, image['src'])
             filename = image["src"].split("/")[-1].split("?")[0].replace("$",'').replace(".JPG",".jpg").replace("~~_26",str(count)).lstrip("(")
             parsed[2] = image["src"]
             outpath = os.path.join(output_folder, filename)
             urlretrieve(image_url, outpath)

我想做的是提取

alt="Sony Cyber-shot DSC-W570 16.1 MP Digital Camera - Silver"

我还想在提取图像时使用 alt 数据作为文件名。

【问题讨论】:

  • 您正在使用image['src'] 获取源。你不能只使用image['alt'] 来获取替代品,还是我误解了你的问题?

标签: python html beautifulsoup scrape


【解决方案1】:

在您的 for 循环中,您只需执行以下操作即可获得它

image.get('alt', '')

这在BeautifulSoup's documentation(“标签的属性”)中有解释。

【讨论】:

  • key 错误意味着特定的 img 标签没有 alt 属性。您确定页面上的每张图片都有与之关联的替代文字吗?
  • 编辑过的答案,它应该适用于@anyaMairead 提到的情况
  • 其实有些没有我想避开那些没有的
  • @GonzaloDelgado 谢谢我如何将 alt 信息添加为文件名..?
  • 取决于您希望文件名的外观,您可以将其混合到示例代码的文件名结构中,尽管那里有很大的改进空间,我想说您问这个在代码审查codereview.stackexchange.com
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多