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



我试图爬网的站点是http://www.boxofficemojo.com/yearly/chart/?yr=2013&p=.htm.我现在关注的具体页面是http://www.boxofficemojo.com/movies/?id=catchingfire.htm.从这一页来看,我有两件事很难理解。首先,我需要得到"国外总金额"(在总终身总金额下)。我不知道该怎么做,因为当我检查元素时,它似乎没有特定的标签,而且周围有很多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'$440,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']

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

最新更新