使用 BeautifulSoup 解析 IMDB

Parsing IMDB with BeautifulSoup

我使用 BeautifulSoup 和 Python 2.7 从 IMDB 的移动站点中删除了以下代码。

我想为剧集编号“1”、标题 'Winter is Coming' 和 IMDB 评分“8.9”创建一个单独的 object。似乎无法弄清楚如何拆分剧集编号和标题。

   <a class="btn-full" href="/title/tt1480055?ref_=m_ttep_ep_ep1">
     <span class="text-large">
      1.
      <strong>
       Winter Is Coming
      </strong>
     </span>
     <br/>
     <span class="mobile-sprite tiny-star">
     </span>
     <strong>
      8.9
     </strong>
     17 Apr. 2011
    </a>

您可以使用 findspan 和 class text-large 定位到您需要的特定元素。

获得所需的 span 后,您可以使用 next 获取包含剧集编号的下一行,并使用 find 定位包含标题

html = """
<a class="btn-full" href="/title/tt1480055?ref_=m_ttep_ep_ep1">
     <span class="text-large">
      1.
      <strong>
       Winter Is Coming
      </strong>
     </span>
     <br/>
     <span class="mobile-sprite tiny-star">
     </span>
     <strong>
      8.9
     </strong>
     17 Apr. 2011
    </a>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
span = soup.find('span', attrs={'text-large'})
ep = str(span.next).strip()
title = str(span.find('strong').text).strip()

print ep
print title

> 1. 
> Winter Is Coming

一旦你有了每个 a class="btn-full",你可以使用跨度 classes 来获得你想要的标签,强标签是带有 [= 的跨度的 child 15=] class 所以你只需要在标签上调用 .strong.text ,对于 css class mobile-sprite tiny-star 的跨度,你需要找到下一个强标签,因为它是跨度的兄弟而不是 child:

h = """<a class="btn-full" href="/title/tt1480055?ref_=m_ttep_ep_ep1">
     <span class="text-large">
      1.
      <strong>
       Winter Is Coming
      </strong>
     </span>
     <br/>
     <span class="mobile-sprite tiny-star">
     </span>
     <strong>
      8.9
     </strong>
     17 Apr. 2011
    </a>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(h)
title = soup.select_one("span.text-large").strong.text.strip()
score = soup.select_one("span.mobile-sprite.tiny-star").find_next("strong").text.strip()

print(title, score)

这给你:

(u'Winter Is Coming', u'8.9')

如果你真的想得到剧集,最简单的方法是将文本拆分一次:

soup = BeautifulSoup(h)
ep, title = soup.select_one("span.text-large").text.split(None, 1)
score = soup.select_one("span.mobile-sprite.tiny-star").find_next("strong").text.strip()

print(ep, title.strip(), score)

哪个会给你:

(u'1.', u'Winter Is Coming', u'8.9')

使用 url html 抓取请求和正则表达式搜索。

import os, sys, requests

frame = ('http://www.imdb.com/title/tt1480055?ref_=m_ttep_ep_ep1')
f = requests.get(frame)
helpme = f.text
import re
result = re.findall('itemprop="name" class="">(.*?)&nbsp;', helpme)
result2 = re.findall('"ratingCount">(.*?)</span>', helpme)
result3 = re.findall('"ratingValue">(.*?)</span>', helpme)
print result[0].encode('utf-8')
print result2[0]
print result3[0]

输出:

Winter Is Coming
24,474
9.0