Python 网络抓取 BeautifulSoup:获取文本和链接

Python webcrawling BeautifulSoup: getting both text and links

我要抓取的网站是 http://www.boxofficemojo.com/yearly/chart/?yr=2013&p=.htm. The specific page I'm focusing on now is http://www.boxofficemojo.com/movies/?id=catchingfire.htm。从这个页面,我无法获得两件事。首先,我需要获得 "Foreign gross" 金额(在 Total Lifetime Grosses 下)。我不确定该怎么做,因为当我检查该元素时,它似乎没有特定的标签,并且周围有大量 css 标签。我怎样才能得到这条数据?

接下来,我要获取每部电影的演员列表。我已经成功地获得了所有附加了链接的演员(通过搜索 a href 标签),但是我无法获得没有链接的演员。

def spider(max_pages):
page = 1
while page <= max_pages:
    url = 'http://www.boxofficemojo.com/yearly/chart/?page=' + str(page) + '&view=releasedate&view2=domestic&yr=2013&p=.htm'
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for link in soup.select('td > b > font > a[href^=/movies/?]'):
        href = 'http://www.boxofficemojo.com' + link.get('href')
        details(href)

        listOfDirectors.append(getDirectors(href))
        str(listOfDirectors).replace('[','').replace(']','')

        listOfActors.append(getActors(href))
        str(listOfActors).replace('[','').replace(']','')
        getActors(href)
        title = link.string
        listOfTitles.append(title)
    page += 1


def getActors(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
tempActors = []
for actor in soup.select('td > font > a[href^=/people/chart/?view=Actor]'):
    tempActors.append(str(actor.string))
return tempActors

我在 getActors 函数中所做的是将每部电影的每个演员放入一个临时列表,然后在 spider() 函数中,我将该列表附加到每部电影的完整列表中。我目前获得演员的方式是:

for actor in soup.select('td > font > a[href^=/people/chart/?view=Actor]'):
    tempActors.append(str(actor.string))

这显然不适用于没有链接的演员。我试过了

for actor in soup.findAll('br', {'class', 'mp_box_content'}):
     tempActors.append(str(actor.string))

但这不起作用,它没有添加任何东西。我怎样才能得到所有的演员,不管他们是否有链接?

要获取 "Foreign Gross",获取包含 "Foreign:" 文本的元素并找到 td 父元素的下一个 td 兄弟元素:

In [4]: soup.find(text="Foreign:").find_parent("td").find_next_sibling("td").get_text(strip=True)
Out[4]: u'0,244,916'

至于演员,可以应用类似的技术:找到Actors:,找到tr父级并找到(text=True)内的所有文本节点:

In [5]: soup.find(text="Actors:").find_parent("tr").find_all(text=True)[1:]
Out[5]: 
[u'Jennifer Lawrence',
 u'Josh Hutcherson',
 u'Liam Hemsworth',
 u'Elizabeth Banks',
 u'Stanley Tucci',
 u'Woody Harrelson',
 u'Philip Seymour Hoffman',
 u'Jeffrey Wright',
 u'Jena Malone',
 u'Amanda Plummer',
 u'Sam Claflin',
 u'Donald Sutherland',
 u'Lenny Kravitz']

请注意,这已证明适用于该特定页面。在其他电影页面上测试它并确保它产生所需的结果。