【问题标题】:Selecting elements using xpath使用 xpath 选择元素
【发布时间】:2019-06-25 04:13:59
【问题描述】:

对 Selenium 来说非常新,但我无法从这个网站选择我想要的元素。在这种情况下,我使用 Chrome 的“复制 XPath 工具”获得了 x_path。基本上,我希望从网站中提取 CID 文本(在本例中为 4004),但我的代码似乎无法做到这一点。任何帮助将不胜感激!

我也尝试过使用 CSS 选择器方法,但它返回相同的错误。

chrome_options = Options()  
chrome_options.add_argument("--headless")  
chrome_options.binary_location = '/Applications/Google Chrome   Canary.app/Contents/MacOS/Google Chrome Canary'

driver= webdriver.Chrome()

chem_name = "D008294"
url = "https://pubchem.ncbi.nlm.nih.gov/#query=" + chem_name
driver.get(url)  


elements = driver.find_elements_by_xpath('//*[@id="collection-results-container"]/div/div/div[2]/ul/li/div/div/div/div[2]/div[2]/div[2]/span/a/span/span')

driver.close()

print(elements.text)

截至目前,这是我收到的错误:'list' object has no attribute 'text'

【问题讨论】:

    标签: selenium


    【解决方案1】:

    这是您可以使用的 xpath。

    //span[.='Compound CID']//following-sibling::a/descendant::span[2]
    

    为什么您的脚本不起作用:我的代码中有 2 个问题。

    elements = driver.find_elements_by_xpath('//*[@id="collection-results-container"]/div/div/div[2]/ul/li/div/div/div/div[2]/div[2]/div[2]/span/a/span/span')
    
    driver.close() # <== don't close the browser until you are done with all your steps on the browser or elements
    
    print(elements.text) # <== you can not get text from list (python will through error here
    

    如何解决:

    CID =  driver.find_element_by_xpath("//span[.='Compound CID']//following-sibling::a/descendant::span[2]").text # <== returning the text using find_element (not find_elements)
    
    driver.close()
    
    print(CID) # <== now you can print `CID` though browser closed as the value already stored in variable.
    

    【讨论】:

      【解决方案2】:

      函数driver.find_elements_by_xpath 返回元素列表。您应该循环获取每个元素的文本,

      像这样:

      for ele in print(elements.text):
          print(ele.text)
      

      或者如果您想匹配第一个元素,请改用driver.find_element_by_xpath 函数。

      【讨论】:

        【解决方案3】:

        使用 xpath 提供的 chrome 总是无法按预期工作。首先你必须知道如何编写 xpath 并在 chrome 控制台中验证它。

        查看这些链接,这有助于您了解 xpaths

        https://www.guru99.com/xpath-selenium.html

        https://www.w3schools.com/xml/xpath_syntax.asp

        在这种情况下,首先找到包含文本 Compound CID 的 span 并移动到 parent span 下到 child a/span/span。类似于 //span[contains(text(),'Compound CID']/parent::span/a/span/span.

        您还需要找到返回单个元素并从中获取文本的元素。如果您使用 findelements,那么它将返回元素列表,因此您需要循环并从这些元素中获取文本。

        【讨论】:

          【解决方案4】:

          xpath: //a[contains(@href, 'compound')]/span[@class='breakword']/span

          你可以使用“href”作为你的属性引用,因为我注意到它对每个组件都有唯一的价值。

          示例: href="https://pubchem.ncbi.nlm.nih.gov/物质/53790330" href="https://pubchem.ncbi.nlm.nih.gov/复合/4004"

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-02-23
            • 2011-11-06
            • 2020-08-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-18
            相关资源
            最近更新 更多