如果您查看前面的页面源代码,会发现其中包含电影名称及其评分。幸运的是,烂番茄(RottenTomatoes)并未动态加载电影列表,因此我们可以直接抓取所需信息。
首先,我们检查页面以了解 HTML 的结构。为此,您可以右键单击电影标题并选择“检查元素”选项。随后应出现如下窗口:
我用红线标出了这张图片中的有用信息。你可以看到,页面以表格形式展示热门电影,且每行表格包含四个单元格(<tr> 元素)。
第一个单元格包含电影的排名位置,第二个单元格包含评分信息(类名为 tMeterScore 的元素),第三个单元格包含电影标题,最后一个单元格则显示评论数量。
了解这一结构后,我们现在可以开始提取所需的信息了。
import requests
from bs4 import BeautifulSoup
links_base = 'https://www.rottentomatoes.com'
scraped_url = 'https://www.rottentomatoes.com/top/bestofrt/'
page = requests.get(scraped_url)
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find("table", class_="table") # We extract just the table code from the entire page
rows = table.findAll("tr") # This will extract each table row, in an array
movies = []
for index, row in enumerate(rows):
if index > 0: # We skip the first row since this row only contains the column names
link = row.find("a") # We get the link from the table row
rating = row.find(class_="tMeterScore") # We get the element with the class tMeterScore from the table row
movies.append({
"link": links_base + link.get('href'), # The href attribute of the link
"title": link.string.strip(), # The strip function removes blank spaces at the beginning and the end of a string
"rating": rating.string.strip().replace(" ", ""), # We remove from the string and the blank spaces
})
print(movies)
运行此代码后,您应得到如下结果:
在此示例中,我们提取表格内容并遍历表格行。由于第一行仅包含列名,我们将跳过它。
对于其余行,我们将继续提取锚点(<a>)元素以及类名为“tMeterScore”的span元素。获取这些元素后,我们便能提取所需信息。
电影标题位于锚点元素内,链接是锚点的“href”属性,评分则位于类名为“tMeterScore”的span元素内。我们只需为每一行创建一个新字典,并将其追加到电影列表中。