gpt4 book ai didi

python - Beautiful Soup - 选择没有类的下一个跨度元素的文本

转载 作者:行者123 更新时间:2023-12-01 02:33:08 25 4
gpt4 key购买 nike

我正在尝试使用 Beautiful Soup 从 rottentomatoes.com 上抓取电影台词。页面源代码很有趣,因为引用直接由跨度类“bold quote_actor”进行,但引用本身位于没有类的跨度中,例如(https://www.rottentomatoes.com/m/happy_gilmore/quotes/): screenshot of web source

我想使用 Beautiful Soup 的 find_all 来捕获所有引用,但不包含 Actor 的名字。我尝试了很多事情但没有成功,例如:

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 选择器来查找包含引号的 span:div 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)

关于python - Beautiful Soup - 选择没有类的下一个跨度元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46564716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com