【发布时间】:2021-05-10 19:42:59
【问题描述】:
我有一些代码可以通过维基百科上的节目或电影的演员表。抓取所有演员的姓名并存储它们。我拥有的当前代码在列表中找到所有<a> 并存储它们的标题标签。目前是这样:
from bs4 import BeautifulSoup
URL = input()
website_url = requests.get(URL).text
section = soup.find('span', id='Cast').parent
Stars = []
for x in section.find_next('ul').find_all('a'):
title = x.get('title')
print (title)
if title is not None:
Stars.append(title)
else:
continue
虽然这部分有效,但有两个缺点:
- 如果演员没有维基百科页面超链接,它就不起作用。
- 它还会抓取它找到的任何其他超链接标题。例如https://en.wikipedia.org/wiki/Indiana_Jones_and_the_Kingdom_of_the_Crystal_Skull 返回
['Harrison Ford', 'Indiana Jones (character)', 'Bullwhip', 'Cate Blanchett', 'Irina Spalko', 'Bob cut', 'Rosa Klebb', 'From Russia with Love (film)', 'Karen Allen', 'Marion Ravenwood', 'Ray Winstone', 'Sallah', 'List of characters in the Indiana Jones series', 'Sexy Beast', 'Hamstring', 'Double agent', 'John Hurt', 'Ben Gunn (Treasure Island)', 'Treasure Island', 'Courier', 'Jim Broadbent', 'Marcus Brody', 'Denholm Elliott', 'Shia LaBeouf', 'List of Indiana Jones characters', 'The Young Indiana Jones Chronicles', 'Frank Darabont', 'The Lost World: Jurassic Park', 'Jeff Nathanson', 'Marlon Brando', 'The Wild One', 'Holes (film)', 'Blackboard Jungle', 'Rebel Without a Cause', 'Switchblade', 'American Graffiti', 'Rotator cuff']
有没有办法让 BeautifulSoup 刮掉每个 <li> 之后的前两个单词?或者甚至是我想要做的更好的解决方案?
【问题讨论】:
-
x.get('title')返回一个字符串,因此您可以只拆分(),只选择前两个“单词”,然后加入()。例如,title = ' '.join(title.split(' ')[:2]).
标签: python beautifulsoup