【问题标题】:Python/Selenium Finding a specific class element, analyzing if it contains a specific span class, if it does, copy the linkPython/Selenium 查找特定的类元素,分析是否包含特定的span类,如果有,复制链接
【发布时间】:2020-03-25 05:02:00
【问题描述】:

尝试创建一个循环遍历我的收件箱并查找所有包含“relative flex”的 div 类的脚本,如果 div 类包含标记为“dn dib-1”的跨度类,则它将以下 href 链接复制并保存到我的列表并移动到下一个 div。

这里是html代码:

   <div class="relative flex">
      <span class="dn dib-l" style="left: -16px;"</span>
      <a href="/conversations/269190401#newest_message" class="flex-auto mv0 f5 fw4 lh-copy light-gray truncate no-underline outline-none">hey how are you?</a>

这是我现在拥有的代码:

link_list = []
sex_list = []
message = browser.find_elements_by_xpath('//*[@class="relative flex"]')
message_new = browser.find_elements_by_xpath('//*[@class="dn dib-l"]')
for item in message:
            link = item.find_element_by_xpath('.//a').get_attribute('href')
            if message_new in message:
                link_list.append(link)

问题: message、message_new 在请求时都包含数据,但是尽管这些类有多个消息,但链接变量仅包含一个元素,而 link_list 不包含任何元素。我需要在我的代码中进行哪些更改才能保存包含此 span 类的 div 类中的所有链接?

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver


    【解决方案1】:

    我会稍微重构一下这段代码以提高效率。对我来说,听起来您想分析所有具有 relative flex 类的 div 元素。然后,如果div 包含某个span 元素,您要保存以下a 项的href 标签。我会这样写:

    # locate the span elements which exist under your desired div
    spans_to_iterate = browser.find_elements_by_xpath("//div[contains(@class, 'relative flex')]/span[contains(@class, 'dn dib-1')]")
    
    link_list = []
    
    # iterate span elements to save the href attribute of a element
    for span in spans_to_iterate:
    
        # get the href element, where 'a' element is following sibling of span.
        link_text = span.find_element_by_xpath("following-sibling::a").get_attribute("href")
        link_list.append(link_text)
    

    这段代码背后的想法是,我们首先检索存在于您想要的div 中的span 元素。在您的问题描述中,您提到您希望在 divspan 元素包含特定类名时保存链接。所以,我们直接查询你提到的元素,而不是先找div然后span

    然后,我们迭代这些span 元素并使用XPath 的following-sibling 表示法来获取紧随其后出现的a 元素。我们可以通过get_attribute 获取href 标签,然后将链接附加到列表中。

    【讨论】:

    • 谢谢,代码有其他问题,但我理解您的思考过程,并将其应用于解决下一步。使用您当前的代码,我收到错误消息“selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/following-sibling: :a"} (Session info: chrome=78.0.3904.108)" 我只是想看看是否可以将选择器更改为其他内容。 spans_to_iterate 具有它应该包含的值的数量,但 link_text/link_list 目前不包含任何内容。
    • 我在一分钟前更正了 XPath 中的一个小错字。正确的语法是following-sibling::a,而不是/following-sibling::a——我相信前导/ 是导致错误的原因。我将这个符号基于这个问题:stackoverflow.com/questions/59107473/…
    【解决方案2】:

    试试这个:

    xpth = "//div[@class='relative flex' and /span[@class='dn dib-l']]//@href"
    links = browser.find_elements_by_xpath(xpth)
    

    【讨论】:

      猜你喜欢
      • 2015-10-10
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 2020-06-18
      • 2020-07-15
      相关资源
      最近更新 更多