【问题标题】:BeautifulSoup webcrawling: How to get piece of textBeautifulSoup webcrawling:如何获取一段文本
【发布时间】:2015-09-11 05:04:30
【问题描述】:

我要抓取的页面是http://www.boxofficemojo.com/yearly/chart/?page=1&view=releasedate&view2=domestic&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" 

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

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

【问题讨论】:

    标签: python web-scraping beautifulsoup web-crawler html-parsing


    【解决方案1】:

    查找Genre: 文本并获取next sibling

    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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2012-07-12
      • 2012-11-13
      • 1970-01-01
      相关资源
      最近更新 更多