【问题标题】:Select the element with shorter name among long ones with partially same in Selenium在 Selenium 中部分相同的长元素中选择名称较短的元素
【发布时间】:2021-09-14 10:59:29
【问题描述】:

所以我想按类名选择一个元素,问题是有2个同名的元素,但其中一个还有一些东西:

<div class="ads-title ads-year">
              ۱۳۹۴ -
              <span>بجنورد</span></div>

<div class="ads-title">پژو پارس ELX XUM</div>

我编写的代码仅用于获取“广告标题”:

driver = webdriver.Chrome(r"./chromedriver")
driver.get('https://mashinbank.com/%D8%AE%D8%B1%DB%8C%D8%AF-%D8%AE%D9%88%D8%AF%D8%B1%D9%88')
names = driver.find_elements_by_class_name('ads-title') 
for name in names:
    print(name.text)

但它给了我他们两个的内容,我的问题是如何将其缩小到不包含在 'ads-title ads-year' 中的 'ads-title' ? 提前谢谢你。

【问题讨论】:

    标签: python selenium web-crawler


    【解决方案1】:

    您可以将其替换为 css_selector 以仅定位一个匹配节点。

    div[class='ads-title']
    

    在代码中:-

    names = driver.find_elements_by_css_selector("div[class='ads-title']") 
    for name in names:
        print(name.text)
    

    但是我看到上面的css selector,有15个匹配节点。

    如果您正在寻找 特定节点 这是

    <div class="ads-title">پژو پارس ELX XUM</div>
    

    那么你可以使用这个xpath

    //div[@class='ads-title' and text()='پژو پارس ELX XUM']
    

    在代码中:

    driver.get('https://mashinbank.com/%D8%AE%D8%B1%DB%8C%D8%AF-%D8%AE%D9%88%D8%AF%D8%B1%D9%88')
    names = driver.find_elements_by_xpath("//div[@class='ads-title' and text()='پژو پارس ELX XUM']")
    for name in names:
        print(name.text)
    

    【讨论】:

    • 谢谢!还有一件事:我选择了“广告颜色”类,但它包含在跨度中:
      سفید دقایقی پیش
      可以删除跨度信息吗?因为我想保存所有图像的颜色而不是跨度信息。
    • 您要在&lt;span style="float: left;"&gt; 此处进行更改吗?
    • 所有 span 标签信息都是额外的,不是必需的,但它在 ads-color 类中。
    • hmm.. 我建议您为此创建一张新票,因为我知道如何更新属性,但恐怕我不知道如何删除它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2023-03-29
    • 2012-03-05
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    相关资源
    最近更新 更多