selenium - 使用 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'
解决方案
这是您可以使用的 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.
推荐阅读
- java - 为什么 m 方法的可见性会以这种方式改变输出?我预计会发生相反的情况
- android - 如何将谷歌自动完成限制为仅搜索城市中的几个街区?
- interface - 如何修复“端口多重驱动”警告 System Verilog
- python - 如何在 python 正则表达式中获取所有可能从字符串中相同位置开始的重叠匹配?
- .htaccess - Htaccess 重写规则仅重定向主网站页面
- django - 使用'loaddata'在django数据库中加载数据的问题
- gcc - Linux Mint 19.1 XFCE下无法编译TPLINK TL-WN822N驱动
- python - 将 url 拆分为目录并转换为 json 树
- react-native - 如何在 ReactNative 中解析 JSON 数据?
- ios - 滚动时UITableView多节冲突