Reputation: 195
I'm trying to capture only the "Other" text, essentially extracting the strong tag elements
<ul class="listing-row__meta">
<li>
<strong>Ext. Color:</strong>
Other
</li>
</ul>
My code so far:
import requests
from bs4 import BeautifulSoup
from csv import writer
response = requests.get('https://www.cars.com/for-sale/searchresults.action/?mdId=21811&mkId=20024&page=1&perPage=100&rd=99999&searchSource=PAGINATION&showMore=false&sort=relevance&stkTypId=28880&zc=11209')
soup = BeautifulSoup(response.text, 'html.parser')
posts = soup.find_all(class_='shop-srp-listings__inner')
with open('posts.csv', 'w') as csv_file:
csv_writer = writer(csv_file)
headers = ['title', 'color', 'price']
csv_writer.writerow(headers)
for post in posts:
title = post.find(class_="listing-row__title").get_text().replace('\n', '').strip()
color = post.find("li").get_text().replace('\n', '').strip()
colorremove = color.strong.extract()
price = post.find("span", attrs={"class": "listing-row__price"}).get_text().replace('\n', '').strip()
csv_writer.writerow([title, colorremove, price])
This particular script doesn't run, prior to this I had just kept the color line and that works fine, but it pics up the "Ext. Color"
Upvotes: 0
Views: 43
Reputation: 84465
You can use stripped_strings on parent class
from bs4 import BeautifulSoup
html = """
<ul class="listing-row__meta">
<li>
<strong>Ext. Color:</strong>
Other
</li>
</ul>
"""
soup = BeautifulSoup(html, "lxml")
firstItem = soup.select_one('.listing-row__meta')
strings = [string for string in firstItem.stripped_strings]
print(strings[1])
Upvotes: 0
Reputation: 11157
You can find
the <strong>
element and then get its next_sibling
:
from bs4 import BeautifulSoup
markup = r"""
<ul class="listing-row__meta">
<li>
<strong>Ext. Color:</strong>
Other
</li>
</ul>
"""
soup = BeautifulSoup(markup, "html.parser")
print(soup.find("strong").next_sibling.strip())
Result:
Other
Upvotes: 1