我正在尝试抓取 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)
中,您在 requests.get()
中使用 url
而不是 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
编辑: 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('------------------------------------')
关于python - 在 Python 中使用 beautifulsoup 抓取 IMDB;搜索结果然后输入链接然后获取年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516539/