Python Selenium save data-id and data-name in file

北城以北 提交于 2020-05-17 06:37:08

问题


I have this HTML Code

<div id="availables" style="height: 472px; overflow-y: scroll;">
  <div class="_instance _personInstance _volunteer" data-id="980200" data-name="Name1">
    <div class="_addButtonPerson">&nbsp;</div>
      Name1
  </div>
  <div class="_instance _personInstance _volunteer" data-id="14069" data-name="Name2">
    <div class="_addButtonPerson">&nbsp;</div>
       Name2
  </div>
  <div class="_instance _personInstance _volunteer" data-id="514633" data-name="Name3">
    <div class="_addButtonPerson">&nbsp;</div>
      Name3
  </div>

Now I want to write the data-id and the data-name into a csv file.

980200, Name1

14069, name2

514633 Name3

etc.

Only I can't get the data out. My code currently looks like this:

    findMember = browser.find_elements_by_xpath("//div[contains(@class, '_instance _personInstance _volunteer')]")
      for element in findMember:
        with open('names.csv', 'w') as n:
          n.write(element.find_element_by_xpath("//div[@data-id]") + ',' + element.find_element_by_xpath("//div[@data-name]"))

There are no error messages - but the file is not created either.

Could you please help me?


回答1:


findMember = browser.find_elements_by_xpath("//div[contains(@class, '_instance _personInstance _volunteer')]") for element in findMember: with open('names.csv', 'w') as n: n.write(element.get_attribute('data-id'), element.text)




回答2:


it takes a while, but now I found the solution for my Problem with help from Satheesh Answer:

findMember = browser.find_elements_by_xpath("//div[contains(@class, '_instance _personInstance _volunteer')]")
with open('names.csv', 'w') as n:
    for element in findMember:
        n.write(element.get_attribute('data-id') + ', ' + element.get_attribute('data-name') + '\n')

Thanks :-)



来源:https://stackoverflow.com/questions/61437043/python-selenium-save-data-id-and-data-name-in-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!