Python、beauthoulsoup或LXML使用CSS标记从HTML解析图像URL

2024-06-30 07:40:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我到处寻找关于beauthoulsoup或LXML如何工作的合理解释。诚然,他们的文档很好,但是对于像我这样的python/编程新手来说,很难理解我在寻找什么。在

无论如何,作为我的第一个项目,我使用Python来解析RSS提要中的post链接——我已经用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>

因此,根据我对文件的理解,我应该能够通过以下内容:

^{pr2}$

以查找具有该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

Tags: name文档divcomhttpstylebostonlxml
3条回答

使用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

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

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

使用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'])

相关问题 更多 >