Как извлечь текст после тега <i class>? - PullRequest
2 голосов
/ 23 июня 2019

Я пытаюсь распечатать текст «Дилер» из класса div с помощью BeautifulSoup, но я не знаю, как его извлечь.

Я пытался напечатать класс i, но текст дилера не вышел

url = 'https://www.carlist.my/used-cars-for-sale/proton/malaysia'
response = requests.get(url, params={'page_number': 1})
soup = BeautifulSoup(response.text, 'lxml')
articles = soup.find_all('article')[:25]
seller_type = articles[4].find('div', class_ = 'item push-quarter--ends listing__spec--dealer')
seller_type_text = articles[4].find('i', class_ = 'icon icon--secondary muted valign--top push-quarter--right icon--user-formal')

print(seller_type.prettify())
print()
print(seller_type_text)

Это вывод, который я получил:

<div class="item push-quarter--ends listing__spec--dealer">
 <i class="icon icon--secondary muted valign--top push-quarter--right icon--user-formal">
 </i>
 Dealer
 <span class="flyout listing__badge listing__badge--trusted-seller inline--block valign--top push-quarter--left">
  <i class="icon icon--thumb-up">
  </i>
  <span class="flyout__content flyout__content--tip visuallyhidden--portable">
   This 'Trusted Dealer' has a proven track record of upholding the best car selling practices certified by Carlist.my
  </span>
 </span>
 <!-- used car -->
 <!-- BMW -->
</div>


<i class="icon icon--secondary muted valign--top push-quarter--right icon--user-formal"></i>

Как мне напечатать слово «Дилер» сразу после i класса и перед классом span?

Может кто-нибудь помочь мне?

Большое спасибо!

Ответы [ 3 ]

1 голос
/ 23 июня 2019

Существует более быстрый способ использования одного из составных имен классов элемента тега i вместе с next_sibling.

Если вы изучите HTML, вы увидите, что «Дилер» является частью родительского div тега i и следует за тегом i; Таким образом, вы можете взять тег i, а затем использовать next_sibling

enter image description here

from bs4 import BeautifulSoup as bs
import requests

r = requests.get('https://www.carlist.my/used-cars-for-sale/proton/malaysia')
soup = bs(r.content, 'lxml')
print(soup.select_one('.icon--user-formal').next_sibling)
0 голосов
/ 23 июня 2019
import requests
from bs4 import BeautifulSoup
url = 'https://www.carlist.my/used-cars-for-sale/proton/malaysia?profile_type=Dealer'
response = requests.get(url, params={'page_number': 1})
soup = BeautifulSoup(response.text, 'lxml')
articles = soup.find_all('article')[:25]
seller_type = articles[4].find('div', class_ = 'item push-quarter--ends listing__spec--dealer')
print(seller_type.contents[2])
0 голосов
/ 23 июня 2019

Посмотрите на свойство содержимого вашего типа_продавца.Вы увидите, что Дилер находится по адресу seller_type.contents [2].Другими словами,

import requests
from bs4 import BeautifulSoup
url = 'https://www.carlist.my/used-cars-for-sale/proton/malaysia?profile_type=Dealer'
response = requests.get(url, params={'page_number': 1})
soup = BeautifulSoup(response.text, 'lxml')
articles = soup.find_all('article')[:25]
seller_type = articles[4].find('div', class_ = 'item push-quarter--ends listing__spec--dealer')
print(seller_type.contents[2])
...