简体   繁体   中英

How to extract multiple elements from XPath Selenium (Python)

I made this XPath

alo1 = driver.find_element(By.XPATH, "//div[@class='txt-block']/span/a/span").text
print(alo1)

but the problem is: i'm getting only the first element, but there is 3 or 4 elements with the same XPath, and i wanted then all.

From page to page the number of elements change from 0 to 4.

How can i do it?

And other thing, do you think is possible to make another XPath? I'm trying to get the name of the producers of the films.

EDIT:

I have a second difficulty. I'm passing this result to an excel sheet, but it needs to be in one line to be printed there, or else will only print the last one. How can it be done? ,

wb = xlwt.Workbook()
ws = wb.add_sheet("A Test Sheet")
driver = webdriver.Chrome()
driver.get('http://www.imdb.com/title/tt4854442/?ref_=wl_li_tt')
labels = driver.find_elements_by_xpath("//div[@class='txt-
block']/span/a/span")
for label in labels:
   print (label.text)
ws.write(x-1,1,label.text)
wb.save("sinopses.xls")

The website for reference: http://www.imdb.com/title/tt4854442/?ref_=wl_li_tt

You can get them all at once, and then get text for each element:

alos = driver.find_elements(By.XPATH, "//div[@class='txt-block']/span/a/span")

for alo in alos:
  print alo.text

For the first question:

FindElement always give only one result , even if the locator matches more than one , it automatically takes the first one.

If locator gives more than one matching result and you want all of them then you should go for findElements

For the second question:

labels = driver.find_elements_by_xpath("//div[@class='txt-
block']/span/a/span")
result = ''
for label in labels:
   result += label.text
   print (result)
ws.write(x-1,1,result)
wb.save("sinopses.xls")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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