【问题标题】:Beautiful Soup - selecting text of next span element with no classBeautiful Soup - 选择没有类的下一个跨度元素的文本
【发布时间】:2018-03-15 20:07:39
【问题描述】:

我正在尝试使用 Beautiful Soup 从 rottentomatoes.com 上抓取电影台词。页面来源很有趣,因为引号直接由跨度类“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 等一起使用的对象中的任何提示。

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    我正在使用 CSS 选择器来查找包含引号的 spansdiv span + span。这将查找 div 内的任何 span 元素并具有 span 类型的直接兄弟元素。

    这样我也得到了包含演员姓名的spans,因此我通过检查它们是否具有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)
    

    【讨论】:

    • 完美!非常感谢。通过仔细查看您的答案,我学到了很多东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 2019-07-10
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多