M
M
Master Ruby2021-08-13 21:24:05
Python
Master Ruby, 2021-08-13 21:24:05

How to get the value of a div element of only a specific class?

<div class="eP0wn _2xJnS"> $192.88<span class="_2plVT">$386</span></div>

I only need to get the value of $192.88! My code:<div class="eP0wn _2xJnS">
r = requests.get(uri, headers={
    'Cookie': '__cf_bm=0a235e3207575e16e9a4ccac4dcfed73c847e88a-1628873409-1800-AR7qE9H2D9fprPq+Aqj4Mpllpk8O'
              '/F3Crz44Ka7eW0Jc4+oER25SkRaotc8ADHEPxsrsPlz1gGra+/Ly+pRHgHg=; _ga=GA1.2.2021608225.1628872175; '
              '_gid=GA1.2.1012835482.1628872175; _gat_gtag_UA_134829663_2=1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0'
})
s4 = BeautifulSoup(r.text, 'lxml')
for elements in s4.find_all('article', '_2Mqpk'):
    price = elements.find('div', 'eP0wn _2xJnS').text

In response, I receive $192.88$386 .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2021-08-14
@Dunaevlad

from lxml import etree
import io

html = '''<div class="eP0wn _2xJnS"> $192.88<span class="_2plVT">$386</span></div>'''

parser = etree.HTMLParser()
tree = etree.parse(io.StringIO(html), parser=parser)

print(tree.xpath('.//div[@class="eP0wn _2xJnS"]')[0].text)

# $192.88

G
Gitley, 2021-08-14
@Gitley

Try .contents[0] instead of .text

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question