BeautifulSoup网络爬行:如何获取一段文本



我试图爬网的页面是http://www.boxofficemojo.com/yearly/chart/?page=1&视图=发布日期&view2=国内&yr=2013&p=.htm.具体来说,我现在关注的是这一页:http://www.boxofficemojo.com/movies/?id=ironman3.htm.

对于第一个链接上的每一部电影,我都想得到类型、运行时间、MPAA评级、外国总收入和预算。我很难得到这个,因为信息上没有识别标签。到目前为止我所拥有的:

import requests
from bs4 import BeautifulSoup
from urllib2 import urlopen
def trade_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')
            title = link.string
            print title, href
            get_single_item_data(href)

def get_single_item_data(item_url):
    source_code = requests.get(item_url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    print soup.find_all("Genre: ")
    for person in soup.select('td > font > a[href^=/people/]'):
        print person.string

trade_spider(1)

到目前为止,这将从原始页面中检索电影的所有标题、链接以及每部电影的演员/人员/导演列表等。现在我正在努力了解这部电影的类型。

我试图以类似的方式来处理这个问题

"for person in soup.select('td > font > a[href^=/people/]'):
        print person.string" 

行,但这不是链接,它只是文本,所以它不起作用。

如何获取每部电影的数据?

查找Genre:文本并获取下一个同级:

soup.find(text="Genre: ").next_sibling.text

演示:

In [1]: import requests
In [2]: from bs4 import BeautifulSoup
In [3]: response = requests.get("http://www.boxofficemojo.com/movies/?id=ironman3.htm")
In [4]: soup = BeautifulSoup(response.content)
In [5]: soup.find(text="Genre: ").next_sibling.text
Out[5]: u'Action / Adventure'

相关内容

最新更新