Python,BeautifulSoup或LXML - 使用CSS标记从HTML解析图像URL

问题描述:

我已经搜索了高和低的一个体面的解释如何BeautifulSoup或LXML的工作。当然,他们的文档非常棒,但对于像我这样的人来说,这是一个python /编程新手,很难破解我正在寻找的东西。Python,BeautifulSoup或LXML - 使用CSS标记从HTML解析图像URL

无论如何,作为我的第一个项目,我正在使用Python解析RSS feed以获得发布链接 - 我已经使用Feedparser完成了此操作。我的计划是,然后刮每个帖子的图像。但对于我的生活,我无法弄清楚如何让BeautifulSoup或LXML做我想做的!我花了几个小时阅读文档,并使用谷歌搜索无济于事,所以我在这里。以下是大图(我的刮脸)的一行。

<div class="bpBoth"><a name="photo2"></a><img src="http://inapcache.boston.com/universal/site_graphics/blogs/bigpicture/shanghaifire_11_22/s02_25947507.jpg" class="bpImage" style="height:1393px;width:990px" /><br/><div onclick="this.style.display='none'" class="noimghide" style="margin-top:-1393px;height:1393px;width:990px"></div><div class="bpCaption"><div class="photoNum"><a href="#photo2">2</a></div>In this photo released by China's Xinhua news agency, spectators watch an apartment building on fire in the downtown area of Shanghai on Monday Nov. 15, 2010. (AP Photo/Xinhua) <a href="#photo2">#</a><div class="cf"></div></div></div> 

所以,根据我的文档的理解,我应该能够通过以下:

soup.find("a", { "class" : "bpImage" }) 

要查找与CSS类的所有实例。那么,它不会返回任何东西。我确信我忽略了一些微不足道的东西,所以我非常感谢你的耐心。

非常感谢您的回复!

对于未来的Google,我会包括我feedparser代码:

#! /usr/bin/python 

# RSS Feed Parser for the Big Picture Blog 

# Import applicable libraries 

import feedparser 

#Import Feed for Parsing 
d = feedparser.parse("http://feeds.boston.com/boston/bigpicture/index") 

# Print feed name 
print d['feed']['title'] 

# Determine number of posts and set range maximum 
posts = len(d['entries']) 

# Collect Post URLs 
pointer = 0 
while pointer < posts: 
    e = d.entries[pointer] 
    print e.link 
    pointer = pointer + 1 

使用lxml的,你可能会做这样的事情:

import feedparser 
import lxml.html as lh 
import urllib2 

#Import Feed for Parsing 
d = feedparser.parse("http://feeds.boston.com/boston/bigpicture/index") 

# Print feed name 
print d['feed']['title'] 

# Determine number of posts and set range maximum 
posts = len(d['entries']) 

# Collect Post URLs 
for post in d['entries']: 
    link=post['link'] 
    print('Parsing {0}'.format(link)) 
    doc=lh.parse(urllib2.urlopen(link)) 
    imgs=doc.xpath('//img[@class="bpImage"]') 
    for img in imgs: 
     print(img.attrib['src']) 
+0

这是完美的。非常感谢你。 – tylerdavis 2010-11-23 17:28:12

您发布查找具有bpImage类的所有a元素的代码。但是,您的示例在img元素上有bpImage类,而不是a。你只需要做到:

soup.find("img", { "class" : "bpImage" }) 
+0

哈哈。当然。这样就会返回带有标签的网址。有没有什么方法可以将这些内容剥离到只有url? – tylerdavis 2010-11-23 17:10:17

使用pyparsing搜索标签是相当直观:

from pyparsing import makeHTMLTags, withAttribute 

imgTag,notused = makeHTMLTags('img') 

# only retrieve <img> tags with class='bpImage' 
imgTag.setParseAction(withAttribute(**{'class':'bpImage'})) 

for img in imgTag.searchString(html): 
    print img.src