我已经编写了一个程序,可以从博客或任何页面中获取所需的信息。接下来,我要实现的是从该页面检索第一个图像,该图像属于相应的帖子(就像Facebook在共享帖子时所做的那样)。
我能够在某种程度上通过使用alt
标记获取第一张图片来实现这一目标(因为许多网站在其徽标和图标等中没有alt标记,第一个应该属于这个帖子)。但在某些情况下,这似乎不起作用。有没有其他(更好的)方法来实现这一目标?
我使用的是python 2.7.9和BeautifulSoup 4.
d = feedparser.parse('http://rss.cnn.com/rss/edition.rss')
for entry in d.entries:
try:
if entry.title is not None:
print entry.title
print ""
except Exception, e:
print e
try:
if entry.link is not None:
print entry.link
print ""
except Exception, e:
print e
try:
if entry.published[5:16] is not None:
print entry.published[5:16]
print ""
except Exception, e:
print e
try:
if entry.category is not None:
print entry.category
print ""
except Exception, e:
print e
try:
if entry.get('summary', '') is not None:
print entry.get('summary', '')
print ""
except Exception, e:
print e
time.sleep(5)
r = requests.get(entry.link, headers = {'User-Agent' : 'Safari/534.55.3 '})
soup = BeautifulSoup(r.text, 'html.parser')
for img in soup.findAll('img'):
if img.has_attr('alt'):
if img['src'].endswith('.jpg') == True or img['src'].endswith('.png') == True:
print img['src']
break
答案 0 :(得分:1)
看一下opengraph模块可能更实际:
https://pypi.python.org/pypi/opengraph/0.5
以你喜欢的方式纠正它。
它将从HTML代码中获取“第一张图像”或使用og:image。
如果您想学习,也可以通过查看源代码来完成。该模块也使用BeautifulSoup。
我需要以下monkeypatch来激活抓取作为后备:
import re
from bs4 import BeautifulSoup
from opengraph import OpenGraph
def parser(self, html):
"""
"""
if not isinstance(html,BeautifulSoup):
doc = BeautifulSoup(html, from_encoding='utf-8')
else:
doc = html
ogs = doc.html.head.findAll(property=re.compile(r'^og'))
for og in ogs:
self[og[u'property'][3:]]=og[u'content']
# Couldn't fetch all attrs from og tags, try scraping body
if not self.is_valid() and self.scrape:
for attr in self.required_attrs:
if not hasattr(self, attr):
try:
self[attr] = getattr(self, 'scrape_%s' % attr)(doc)
except AttributeError:
pass
OpenGraph.parser = parser
OpenGraph.scrape = True # workaround for some subtle bug in opengraph
您可能需要处理图片来源中的亲戚网址,但使用urljoin来自urlparse非常简单
import opengraph
...
page = opengraph.OpenGraph(url=link, scrape=True)
...
if page.is_valid():
...
image_url = page.get('image', None)
...
if not image_url.startswith('http'):
image_url = urljoin(page['_url'], page['image'])
(为了简洁起见,省略了一些检查)