[英]Python & Selenium: what's the best way to hierarchically select data from html elements?
As an exercise for learning Python and Selenium, I'm trying to write a script that checks a web page with all kinds of commercial deals, find all the specific food deals (class name 'tag-food'), put them in a list (elem), then check which ones contain the text 'sushi', and for those elements extract the html element which contains price.作为学习 Python 和 Selenium 的练习,我正在尝试编写一个脚本来检查带有各种商业交易的 web 页面(找到所有特定的交易名称),将食物交易放在列表标签中(elem),然后检查哪些包含文本“sushi”,并为这些元素提取包含价格的 html 元素。 And print the results.
并打印结果。
I have:我有:
elem = driver.find_elements_by_class_name('tag-food')
i = 0
while i < len(elem):
source_code = elem[i].get_attribute("innerHTML")
# ?? how to check if source_code contains 'sushi'?
# ?? if true how to extract price data?
i = i + 1
driver.quit()
What's the best and most direct way to do these checks?进行这些检查的最佳和最直接的方法是什么? Thanks!
谢谢!
I don't think you need a while loop for this.我认为你不需要一个while循环。 Also, you would be looking for a
text
value, not innerHTML
此外,您将寻找
text
值,而不是innerHTML
You can make it more simple like this:你可以像这样使它更简单:
for row in driver.find_elements_by_class_name('tag-food'):
if "sushi" in row.get_attribute("innerText"):
print("Yes this item has sushi")
# find element to grab price, store in variable to do something else with
else:
print("No sushi in this item")
Or even just this, depending on how the text in the HTML is structured:甚至只是这个,取决于 HTML 中的文本的结构:
for row in driver.find_elements_by_class_name('tag-food'):
if "sushi" in row.text:
print("Yes this item has sushi")
# find element to grab price, store in variable to do something else with
else:
print("No sushi in this item")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.