问题
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"> </div>
Name1
</div>
<div class="_instance _personInstance _volunteer" data-id="14069" data-name="Name2">
<div class="_addButtonPerson"> </div>
Name2
</div>
<div class="_instance _personInstance _volunteer" data-id="514633" data-name="Name3">
<div class="_addButtonPerson"> </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