python - 从属于帖子的网站获取第一张图片

标签 python python-2.7 web-scraping beautifulsoup

我编写了一个程序,可以从博客或任何页面中获取所需的信息。接下来,我想要实现的是从该页面检索属于相应帖子的第一张图片(就像 Facebook 在分享帖子时所做的那样)。

我能够在某种程度上通过获取带有 alt 标签的第一张图片来实现这一点(因为许多网站的 Logo 和图标等中没有 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

最佳答案

看看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

您可能需要处理图像源中的相关 URL,但使用 urlparse 中的 urljoin 非常简单

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

(为简洁起见,代码片段中省略了一些检查)

关于python - 从属于帖子的网站获取第一张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597225/

相关文章:

python - 缺少一些 PIL.ImageFile 属性,如 LOAD_TRUNCATED_IMAGES

Python - pyplot.quiver(X, Y, U, V) 未绘制预期结果

python - 如何检查python中包含的列表中的项目

python-2.7 - 高分辨率再分析数据

python - Scrapy 关注并抓取下一页

python - 当我与远程桌面断开连接时,PyKeyboard.tap_key() 不起作用

python - Matplotlib 错误 : LaTeX was not able to process the following string: 'lp'

python-2.7 - TypeError : 'PathCollection' object is not iterable when adding second legend to plot

python - 这个 xPath 没有给出任何结果,有什么原因吗?

javascript - 抓取 html 页面结果..顺序不正确