首页 文章

美丽的汤 - 选择下一个 Span 元素的文本没有类

提问于
浏览
1

我试图用美丽的汤来刮掉rottentomatoes.com的电影报价 . 页面源非常有趣,因为引号直接由span类"bold quote_actor"继续,但引用本身在没有类的范围内,例如(https://www.rottentomatoes.com/m/happy_gilmore/quotes/):screenshot of web source

我想使用Beautiful Soup的find_all来捕获所有引号,而没有演员的名字 . 我尝试了许多没有成功的事情,例如:

moviequotes = soup(input)
for t in web_soup.findAll('span', {'class':'bold quote_actor'}):
    for item in t.parent.next_siblings:
        if isinstance(item, Tag):
            if 'class' in item.attrs and 'name' in item.attrs['class']:
                break
            print (item)

我非常感谢有关如何导航此代码以及将生成的纯文本引号定义为我与Pandas等使用的对象的任何提示 .

1 回答

  • 2

    我正在使用CSS选择器来查找包含引号的 spansdiv span + span . 这将查找 div 中的任何 span 元素,并且具有 span 类型的直接同级元素 .

    这样我也得到包含actor名称的 span ,所以我通过检查它们是否具有 classstyle 属性来过滤它们 .

    import bs4
    import requests
    
    url  = 'https://www.rottentomatoes.com/m/happy_gilmore/quotes/'
    page = requests.get(url).text
    soup = bs4.BeautifulSoup(page, 'lxml')
    
    # CSS selector
    selector = 'div span + span'
    
    # find all the span elements which are a descendant of a div element
    # and are a direct sibling of another span element 
    quotes = soup.select(selector)
    
    # now filter out the elements with actor names
    data = []
    
    for q in quotes:
        # only keep elements that don't have a class or style attribute
        if not (q.has_attr('class') or q.has_attr('style')):
            data.append(q)
    
    for d in data:
        print(d.text)
    

相关问题