简体   繁体   English

Python Selenium 一个元素与不同的 xpath 使用 Try-Loop

[英]Python Selenium one element with different xpath using Try-Loop

there are some elements with different xpath like 'code' in the website:网站中有一些具有不同 xpath 的元素,例如“代码”:

.td[1]/div[4]/div
.td[1]/div[3]/div
null

if the xpath =.td[1]/div[4]/div, then there should be another ISIN code in.td[1]/div[3]/div I want to access them all with:如果 xpath =.td[1]/div[4]/div,那么在 .td[1]/div[3]/div 中应该有另一个 ISIN 代码我想通过以下方式访问它们:

driver.get('https://www.chinabondconnect.com/en/Primary/Primary-Information/Onshore.html')
wait = WebDriverWait(driver, 30)
driver.find_element_by_link_text('Others').click()

try: 
    codes=[code.get_attribute('textContent') for code in driver.find_elements_by_xpath("//table[@id='tb7']//tr[starts-with(@class,'tb2tr pg')]//td[1]/div[4]/div")]
    ISINs=[ISIN.get_attribute('textContent') for ISIN in driver.find_elements_by_xpath("//table[@id='tb7']//tr[starts-with(@class,'tb2tr pg')]//td[1]/div[3]/div")]
except:
    try:
      codes=[code.get_attribute('textContent') for code in driver.find_elements_by_xpath("//table[@id='tb7']//tr[starts-with(@class,'tb2tr pg')]//td[1]/div[3]/div")]                 
    except:
      codes = 'null'
#dateframe=...               

But it will not return all issuers in the website, only just few ones, not sure why this happened, any help will be appreciated!但它不会返回网站上的所有发行人,只有少数几个,不知道为什么会这样,任何帮助将不胜感激!

So far I have something like this.到目前为止,我有这样的事情。 Which inserts null for no child elements of that td.其中插入 null 用于该 td 的没有子元素。

driver.get('https://www.chinabondconnect.com/en/Primary/Primary-Information/Onshore.html')
driver.find_element_by_link_text('Others').click()
codes=[]
ISINs=[]
rows=driver.find_elements_by_xpath("//table[@id='tb7']//tr[starts-with(@class,'tb2tr pg')]")
for row in rows:
    try: 
        codes.append(row.find_element_by_xpath("./td[1]/div[4]/div").get_attribute('textContent'))
    except:
        codes.append('null')
    try: 
        ISINs.append(row.find_element_by_xpath("./td[1]/div[3]/div").get_attribute('textContent'))
    except:
        ISINs.append('null')
        
dataframe=pd.DataFrame({'codes':codes,'ISINs':ISINs}) 
print (dataframe)

Import进口

import pandas as pd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM