【发布时间】:2021-04-01 19:25:48
【问题描述】:
首先,我是网络抓取的新手,所以如果我的行话不正确,我深表歉意。我正在尝试从这个 IMDB 1000 强电影网站将四个项目(电影标题、运行时间、类型和年份)放入 Pandas DF。我正在学习一个教程 (https://www.dataquest.io/blog/web-scraping-python-using-beautiful-soup/),该教程首先分解了该过程,以便您从 HTML 元素列表(在本例中为一部电影)中提取单个元素并获取所需的属性(电影标题、运行时间、流派和年份)使用 HTML 标签。但是,当我尝试继续学习本教程并使用选择器从所有电影中获取主标签下的所有元素时,我最终得到了一个空列表。
所以这是该过程的第一部分(从 HTML 元素列表中提取单个元素并获取该元素(电影)所需的属性:
# Let's get the html from https://www.imdb.com/search/title/?groups=top_1000&sort=runtime,asc.
# We’ll need to first download it using the requests.get method.
import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib as mpl
page = requests.get("https://www.imdb.com/search/title/?groups=top_1000&sort=runtime,asc")
# create an instance of the BeautifulSoup class to parse our document
soup = BeautifulSoup(page.content, 'html.parser')
top_1000 = soup.find(id = "main") # Find outermost element containing all relevant movie info
film_items = top_1000.find_all(class_='lister-item mode-advanced') # Get the element containing the list of films
first_film = film_items[0] # Get first film in list
print(first_film.prettify())
tags = first_film.find_all('a') # Get all <a tags
title = tags[1].text # Title is embedded in the second item in this list
genre = first_film.find(class_='genre').get_text()
year = first_film.find(class_="lister-item-year text-muted unbold").get_text()
runtime = first_film.find(class_="runtime").get_text()
print(title)
print(genre)
print(year)
print(runtime)
输出:
小夏洛克
动作、喜剧、爱情 (1924)
45 分钟
但是...当我使用选择器获取所有电影的数据时,它返回一个空列表
# Select all items with the class genre inside an item with the class lister-item mode-advanced in top_1000.
# Use a list comprehension to call the get_text method on each BeautifulSoup object.
genre = top_1000.select(".lister-item mode-advanced .genre")
genres = [g.get_text() for g in genre]
print(genres)
输出:
[]
我想也许在调用选择器时我必须包含每个嵌套元素,但我尝试调用嵌套在“lister-item mode-advanced”下方的元素,它也返回了一个空列表。事实上,当我在选择器中只包含“lister-item mode-advanced”时,我得到了一个空白列表。我逐字阅读教程,但这似乎不起作用。对于这方面的任何帮助,我将不胜感激,对于任何语言差异,我再次表示歉意——我是使用 HTML 的新手。
【问题讨论】:
标签: python html beautifulsoup