2011-05-08 146 views
1

图像链接从HTML/RSS网页摘要蟒蛇:从HTML

[...]<div class="..." style="..."></div><p><a href="..." 
<img alt="" heightt="" src="http://link.to/image" 
width="" /></a><span style="">[...] 

我想要得到的图片src链接 “http://link.to/image.jpg”。我如何在Python中做到这一点?谢谢。

+1

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2011-05-08 11:05:15

+0

是它的HTML或RSS?这是一个重要的区别。正确的答案是使用正确的解析器,我相信Python有这些解析器。 – svick 2011-05-08 11:18:52

+0

好的RSS我应该使用解析器,但如果它是html? – SandyBr 2011-05-08 11:21:25

回答

0

也许你应该阅读Regex Howto教程,并在StackOverflow的一个常见问题,从中说,只要你是在处理个XML(HTML)不使用正则表达式,而是用良好的解析器和你的情况,BeautifulSoup是一个开始。

使用正则表达式,你会做这样得到的图片链接:

import re 
pattern = re.compile(r'src="(http://.*\.jpg)"') 
pattern.search("yourhtmlcontainingtheimagelink").group(1) 
+1

从使用正则表达式的先发制人的劝阻,我喜欢它:) – Acorn 2011-05-08 11:36:10

+0

如果图像是PNG会怎么样:我会使用pattern = re.compile(r'src =“(。*?)”') – SandyBr 2011-05-08 11:42:00

+0

'jpg'你可以使用'png'。如果你这样做,它会给所有的src链接(.html等),而不仅仅是图像。 – 2011-05-08 11:45:57

0

为了增加svick的回答, 尝试使用BeautifuSoup分析器,它在过去为我工作。

4

lxml是工作的工具。

要刮去所有从网页图像会是如此简单:

import lxml.html 

tree = lxml.html.parse("http://example.com") 
images = tree.xpath("//img/@src") 

print images 

,并提供:

['/_img/iana-logo-pageheader.png', '/_img/icann-logo-micro.png']

如果它是一个RSS feed,你会想分析它与lxml.etree

0

使用urllib而beautifulsoup:

import urllib 
from BeautifulSoup import BeautifulSoup 

f = urllib.urlopen(url) 
page = f.read() 
f.close()   
soup = BeautifulSoup(page) 
for link in soup.findAll('img'): 
    print "IMAGE LINKS:", link.get('data-src')