首页 > 解决方案 > 使用 xpath 选择元素

问题描述

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

解决方案


这是您可以使用的 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.

推荐阅读