впервые использую BeautifulSoup. Попытка получить значение с веб-сайта со следующей структурой:
<div class = "overview">
<i class = "fa fa-instagram"></i>
<div class = "overflow-h">
<small>Value #1 here</small>
<small>131,390,555</small>
<div class = "progress progress-u progress-xxs">
<div style = "width: 13%" aria-valuemax = "100" aria-valuemin = "0" aria-valuenow = "92" role = "progressbar" class = "progress-bar progress-bar-u">
</div>
</div>
</div>
</div>
<div class = "overview">
<i class = "fa fa-facebook"></i>
<div class = "overflow-h">
<small>Value #2 here</small>
<small>555</small>
<div class = "progress progress-u progress-xxs">
<div style = "width: 13%" aria-valuemax = "100" aria-valuemin = "0" aria-valuenow = "92" role = "progressbar" class = "progress-bar progress-bar-u">
</div>
</div>
</div>
</div>
Хочу второй <small>131,390,555</small>
в первый <div class = "overview"></div>
Это код, который я пытаюсь использовать:
# Get the hashtag popularity and add it to a dictionary
for hashtag in hashtags:
popularity = []
url = ('http://url.com/hashtag/'+hashtag)
r = requests.get(url, headers=headers)
if (r.status_code == 200):
soup = BeautifulSoup(r.content, 'html5lib')
overview = soup.findAll('div', attrs = {"class":"overview"})
print overview
for small in overview:
popularity.append(int(small.findAll('small')[1].text.replace(',','')))
if popularity:
raw[hashtag] = popularity[0]
#print popularity[0]
print raw
time.sleep(2)
else:
continue
Код работает до тех пор, пока второй <small>-value
заполнен в обоих div-overviews
. Мне действительно нужно только второе маленькое значение из первого обзора-div.
Я пытался получить это так:
overview = soup.findAll('div', attrs = {"class":"overview"})[0]
Но я получаю только эту ошибку:
self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'findAll'
Также есть ли способ не «сломать» сценарий, если он вообще не мал? (Пусть скрипт просто заменит пустое значение нулем и продолжит)
Если вам просто нужен 2-й маленький тег только в 1-м div, это будет работать:
soup = BeautifulSoup(r.content, 'html.parser')
overview = soup.findAll('div', class_ = 'overview')
small_tag_2 = overview[0].findAll('small')[1]
print(small_tag_2)
Если вы хотите, чтобы 2-й маленький тег был в каждом обзорном блоке, выполните итерацию, используя цикл:
soup = BeautifulSoup(r.content, 'html.parser')
overview = soup.findAll('div', class_ = 'overview')
for div in overview:
small_tag_2 = div.findAll('small')[1]
print(small_tag_2)
Примечание. Я использовал html.parser вместо html5lib. Если вы умеете работать с html5lib, то это ваш выбор.
вы можете использовать индекс, но я предлагаю использовать селектор CSS и nth-child()
soup = BeautifulSoup(html, 'html.parser')
# only get first result
small = soup.select_one('.overview small:nth-child(2)')
print(small.text.replace(',',''))
# all results
secondSmall = soup.select('.overview small:nth-child(2)')
for small in secondSmall:
popularity.append(int(small.text.replace(',','')))
print(popularity)