首页 > 解决方案 > 如何获取锚标签内的元素?

问题描述

请原谅我对 Selenium 和 python 中的网络抓取非常陌生。我正在尝试抓取超市网站的内容,该网站在 html 中有以下部分

<div class="itemDescription">
            <meta itemprop="priceCurrency" content="INR">
            <meta itemprop="price" content="23.00">
        <h4 class=""><strong class="price js-effective-mrp" data-currency="₹">₹ 23.00 </strong>
                                    <s class="js-actual-mrp" style="display:none;"></s>
                                <br><a href="/fresh-onion-red-v-1-kg-p.php" class="">Fresh Onion Red <span class="item-quantity">1 Kg</span></a></h4>
                    </div>

我需要产品的价格、数量和名称。

下面是我编写的代码,但它没有正确解析元素。

div = driver.find_element_by_class_name('itemDescription')
sname =div.find_element_by_css_selector('a').get_attribute('href')
squantity =driver.find_elements_by_class_name('item-quantity')
sprice = driver.find_elements_by_xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "js-effective-mrp", " " ))]')

请帮忙

标签: pythonseleniumselenium-webdriverweb-scrapingweb-crawler

解决方案


试试这个 xPath 的价格:

//strong[@class='price js-effective-mrp' and @data-currency='₹']

或者如果你想要所有货币:

//strong[@class='price js-effective-mrp']

这是链接:

//div[@class='itemDescription']//a

这是数量:

//span[@class = 'item-quantity']

例子:

sname = driver.find_element_by_xpath("//div[@class='itemDescription']//a")
squantity = driver.find_element_by_xpath("//span[@class = 'item-quantity']")
sprice = driver.find_element_by_xpath("//strong[@class='price js-effective-mrp' and @data-currency='₹']")

print(squantity.text) # prints quantity
print(sname.text) # prints name
print(sprice.text) # prints price

根据您的反馈,您无法从列表中获取文本,但您可以从列表中的每个元素中获取文本,如下所示:

sname_list = driver.find_elements_by_xpath("//div[@class='itemDescription']//a")
for sname in sname_list:
    print(sname.text) # print the text of every element in the list

推荐阅读