【问题标题】:Python & Selenium: what's the best way to hierarchically select data from html elements?Python & Selenium:从 html 元素中分层选择数据的最佳方法是什么?
【发布时间】:2021-05-16 05:42:44
【问题描述】:

作为学习 Python 和 Selenium 的练习,我正在尝试编写一个脚本来检查包含各种商业交易的网页,找到所有特定的食品交易(类名 'tag-food'),把它们在列表 (elem) 中,然后检查哪些包含文本“寿司”,并为这些元素提取包含价格的 html 元素。并打印结果。

我有:

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()

进行这些检查的最佳和最直接的方法是什么?谢谢! ????

【问题讨论】:

  • 您可以编写一个 xpath 表达式来匹配它。 //*[@class="tag-food"][contains(., "sushi")]//[@itemprop="price"] - 我只是在猜测 html,因为您没有显示任何内容

标签: python selenium


【解决方案1】:

我认为你不需要一个 while 循环。此外,您将寻找 text 值,而不是 innerHTML

你可以像这样让它更简单:

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")

或者甚至只是这个,取决于 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-23
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2010-09-28
    • 1970-01-01
    相关资源
    最近更新 更多