2017-10-04 59 views
1

我试图用美丽的汤从rottentomatoes.com刮电影报价。页面源是有趣的,因为报价直接由跨度类“bold quote_actor”继续,但报价本身处于没有类的跨度中,例如, (https://www.rottentomatoes.com/m/happy_gilmore/quotes/): screenshot of web source美丽的汤 - 选择没有类的下一个跨度元素的文本

我想用美丽的汤的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等。

回答

0

我使用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) 
+0

完美!非常感谢你。我从密切审查你的答案中学到了很多东西。 – user8422605