python - 如何获取锚标签内的元素?
问题描述
请原谅我对 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", " " ))]')
请帮忙
解决方案
试试这个 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
推荐阅读
- vue.js - 如何在另一个路由器视图上捕获 Vue3 + Mitt 事件?
- spring-boot - 执行器端点未显示
- elasticsearch - 连接到现有弹性搜索的 Graylog 显示 503
- r - 如何用 bnlearn 表示领域知识信息
- javascript - 如何根据 React Native 表单中的字段值更新其他字段?
- google-sheets - 谷歌表时差计算
- django - 如何为聊天应用消息进行分页
- c# - 在 Visual Studio 中生成服务
- go - 浏览器在执行 http.Get in rest API 时使用 golang 返回空响应
- dc.js - 绘制 javascript 交叉过滤器维度的各个方面(使用 d3 和交叉过滤器的数量与时间)