簡體   English   中英

Beautiful Soup - 選擇沒有類的下一個跨度元素的文本

[英]Beautiful Soup - selecting text of next span element with no class

我正在嘗試使用 Beautiful Soup 從 rottentomatoes.com 上抓取電影台詞。 頁面源很有趣,因為引號直接由跨度類“bold quote_actor”處理,但引號本身在沒有類的跨度中,例如( https://www.rottentomatoes.com/m/happy_gilmore/quotes / ):網頁源碼截圖

我想使用 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 等一起使用的對象的任何提示。

我正在使用 CSS 選擇器來查找包含引號的spansdiv span + span 這將查找div內的任何span元素,並且具有類型為span的直接兄弟元素。

通過這種方式,我還獲得了包含演員姓名的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM