首页 > 解决方案 > 无法使用 Beautiful Soup 和 Selenium 遍历元素以刮取烂番茄评级数据

问题描述

我试图找到包含评级数据的元素,但我不知道如何遍历它(下面链接的图片)。评论评分和收视率的 span 元素属于同一类 (mop-ratings-wrap__percentage)。我试图通过分别遍历它们各自的 div('mop-ratings-wrap__half' 和 'mop-ratings-wrap__half Audience-score')来获取这些元素,但我收到了这个错误:

runfile('/Users/*/.spyder-py3/temp.py', wdir='/Users/*/.spyder-py3')
Traceback (most recent call last):

  File "/Users/*/.spyder-py3/temp.py", line 22, in <module>
    cr=a.find('span', attrs={'class':'mop-ratings-wrap__percentage'})

TypeError: find() takes no keyword arguments

这是我的代码:

# -*- coding: utf-8 -*-
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

driver = webdriver.Chrome("/Users/*/Downloads/chromedriver")


critics_rating=[]
audience_rating=[]
driver.get("https://www.rottentomatoes.com/m/bill_and_ted_face_the_music")

content = driver.page_source
soup = BeautifulSoup(content, "lxml")

for a in soup.find('div', attrs={'class':'mop-ratings-wrap__half'}):
      cr=a.find('span', attrs={'class':'mop-ratings-wrap__percentage'})
      critics_rating.append(cr.text)


for b in soup.find('div', attrs={'class':'mop-ratings-wrap__half audience-score'}):
      ar=b.find('span', attrs={'class':'mop-ratings-wrap__percentage'})
      audience_rating.append(ar.text) 

print(critics_rating)
        
    
 

我正在关注这篇文章:https ://www.edureka.co/blog/web-scraping-with-python/#demo

这是我要提取的数据

标签: pythonseleniumweb-scrapingbeautifulsouprotten-tomatoes

解决方案


我怀疑

soup.find()

返回一个字符串而不是您期望的 bs4 对象。因此你在打电话

"somestring".find()

它不接受关键字参数。

(我会对此发表评论,但我缺乏声誉,抱歉)


推荐阅读