python - 使用 Python 和 Beautiful Soup 进行 HTML 抓取(来自 IMDb)
问题描述
例如,我想从此页面获取电影评级并逐行打印评级,我已经提取了名称和 BS4 的发行年份,但不知道如何处理评级......
import requests
from bs4 import BeautifulSoup
import urllib.request
url = urllib.request.urlopen('http://imdb.com/list/ls097228983/')
content = url.read()
soup = BeautifulSoup(content, 'lxml')
for div in soup.findAll('h3', attrs={'class':'lister-item-header'}):
#print(div.find('a')['href'])
#print("**")
#print(div)
year = div.find('span', attrs={'class':'lister-item-year text-muted unbold'})
year = str(year)
year = year.replace('<span class="lister-item-year text-muted unbold">', '')
year = year.replace('</span>', '')
name = div.find('a').contents[0]
print(name + ' ' + year)
>> I want: Solaris (1972) 8.1
解决方案
您需要更改'class':'lister-item-header'
为父'class':'lister-item-content'
类才能获得评级。
import requests
from bs4 import BeautifulSoup
import urllib.request
url = urllib.request.urlopen('http://imdb.com/list/ls097228983/')
content = url.read()
soup = BeautifulSoup(content, 'lxml')
for div in soup.findAll('div', {'class':'lister-item-content'}):
#print(div.find('a')['href'])
#print("**")
#print(div)
year = div.find('span', attrs={'class':'lister-item-year text-muted unbold'})
year = str(year)
year = year.replace('<span class="lister-item-year text-muted unbold">', '')
year = year.replace('</span>', '')
name = div.find('a').contents[0]
rating = div.find('span',class_='ipl-rating-star__rating').text
# print(rating)
# you could also format string.
print(f'{name} {year} {rating}'.format(name, year, rating))
print(name + ' ' + year + " " +rating)
推荐阅读
- python - Python:font_name 和粗体属性在 kivy 中不能一起使用
- sql - Bigquery SQL 代码以获取最早的联系
- file - 输出出现字符串的行号
- angular - Angular 6 - 为从另一个数组中检索的数组本身检索的每个对象创建不同的输入
- python - 带有 2 个 y 轴的分组箱线图,每 x 刻度 2 个绘制变量
- r - 使用 foreach 函数并行计算
- php - 如何在jQuery数组中插入php的while循环数据?
- maven - Nexus Repository 3 (NXRM3):删除快照任务不删除带时间戳的工件
- xml - 我可以根据另一个属性的值通过 XSLT 强制 XML 属性吗?
- spring - 如何在 Spring 集成中动态更改 InboundChannelAdapter 的轮询器 cron