Skip to main content
 首页 » 编程设计

python之在 Python 中使用 beautifulsoup 抓取 IMDB;搜索结果然后输入链接然后获取年份

2024年10月17日10TianFang

我正在尝试抓取 IMDB 以搜索特定标题,在搜索结果中输入第一个链接,然后打印电影发行的年份(以及后来的其他信息),但我似乎无法弄清楚将 html 的哪一部分放入 .find()。

第一个函数起作用并收集原始 url 并将其与新的 url 的第二部分(用于电影页面)连接起来。

感谢您的帮助,这几天一直卡在这个问题上!

from bs4 import BeautifulSoup 
import requests 
from urllib.parse import urljoin # For joining next page url with base url 
 
search_terms = input("What movie do you want to know about?\n> ").split() 
 
url = "http://www.imdb.com/find?ref_=nv_sr_fn&q=" + '+'.join(search_terms) + '&s=all' 
 
def scrape_find_next_page(url): 
    headers = {'User-Agent': 'Mozilla/5.0'} 
    response = requests.get(url, headers=headers) 
    soup = BeautifulSoup(response.text, "html.parser") 
 
    next_page = soup.find('td', 'result_text').find('a').get('href') 
 
    return next_page 
 
 
next_page_url = scrape_find_next_page(url) 
 
new_page = urljoin(url, next_page_url) 
 
 
 
def scrape_movie_data(next_page_url): 
    headers = {'User-Agent': 'Mozilla/5.0'} 
    response = requests.get(url, headers=headers) 
    soup = BeautifulSoup(response.text, "html.parser") 
 
    title_year = soup.find('span','titleYear').find('a').get_text() 
 
    return title_year 
 
print(scrape_movie_data(new_page)) 

请您参考如下方法:

第一个问题:在 scrape_movie_data(next_page_url) 中,您使用 url 而不是 requests.get() 中的 next_page_url > 所以你读错了页面。

response = requests.get(next_page_url, headers=headers) 

第二个问题:你必须在 find() 中使用 {'id': 'titleYear'}

title_year = soup.find('span', {'id': 'titleYear'}).find('a').get_text() 

最终版本:

def scrape_movie_data(next_page_url): 
    headers = {'User-Agent': 'Mozilla/5.0'} 
    response = requests.get(next_page_url, headers=headers) 
    soup = BeautifulSoup(response.text, "html.parser") 
 
    title_year = soup.find('span', {'id': 'titleYear'}).find('a').get_text() 
 
    return title_year 

编辑:检查 Google 中的 IMDB API。一些有趣的结果

SO - IMDB API to retrieve character information

SO - Does IMDB provide an API?

而且您可以获得 JSON 格式的结果,因此您无需抓取。

其他门户:

OMDb API -The Open Movie Database

The Movie DB API


编辑: JSON 数据

import requests 
 
url = 'http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q={}' 
#url = 'http://www.imdb.com/xml/find?json=1&nr=1&nm=on&q={}' 
 
headers = {'User-Agent': 'Mozilla/5.0'} 
 
title = input("Title: ").split() 
 
response = requests.get(url.format(title[0]), headers=headers) 
 
data = response.json() 
 
for x in data['title_popular']: # data['title_approx']: 
    print('title:', x['title']) 
    print(' year:', x['title_description'][:4]) 
    print('---') 
    print('  id:', x['id']) 
    print('name:', x['name']) 
    print('        title:', x['title']) 
    print('episode_title:', x['episode_title']) 
    print('title_description:', x['title_description']) 
    print('      description:', x['description']) 
    print('------------------------------------')