【问题标题】:Detect image src from html using python and regular expressions?使用python和正则表达式从html中检测图像src?
【发布时间】:2012-11-01 16:05:28
【问题描述】:

我想使用python从html代码的img标签中检测图像的src属性。我认为正则表达式可以完成这项工作。我创建了一个正则表达式

\<img .*src="(.*)".*/\>

但是有很多可能的方式来使用img标签比如

<img src="images/first.png" alt="" />
<img src="images/first.png" alt="">
<img  alt="" src="images/first.png" />
<img  alt="" width="100" src="images/first.png" height="200">

所以我的问题是,上述正则表达式是否足以完成任务? 任何人都可以提供更好的选择吗?

【问题讨论】:

  • Can any one give a better option - 是的,使用 lmxl.htmlbs4 - 但根据评论 - I cant use any other libraries in this project ...
  • 通过选项我的意思是更好的正则表达式。
  • @MuhammedKK:抱歉,我们通常不帮助人们在脚上开枪。正则表达式对于这项工作来说是错误的工具

标签: python html regex parsing


【解决方案1】:

改用 HTML 解析器,Python 有几个可供选择:

元素树示例:

from xml.etree import ElementTree

tree = ElementTree.parse('filename.html')
for elem in tree.findall('img'):
    print elem['src']

【讨论】:

    【解决方案2】:

    你可以使用漂亮的库 BeautifulSoup

    【讨论】:

    • 我不能在这个项目中使用任何其他库。
    • @MuhammedKK 那你不能很好地解决这个问题。我想知道为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多