Python Selenium 将数据 ID 和数据名称保存在文件中 [英] Python Selenium save data-id and data-name in file

查看:34
本文介绍了Python Selenium 将数据 ID 和数据名称保存在文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 HTML 代码

<div class="_instance _personInstance _volunteer";数据 ID=980200";数据名称=名称1"><div class="_addButtonPerson"></div>姓名1

<div class="_instance _personInstance _volunteer";数据 ID =14069";数据名称=名称2"><div class="_addButtonPerson"></div>姓名2

<div class="_instance _personInstance _volunteer";数据 ID =514633";数据名称=名称3"><div class="_addButtonPerson"></div>姓名 3

现在我想将 data-id 和 data-name 写入一个 csv 文件.

<块引用>

980200,姓名 1

14069,名称 2

514633 名称 3

只有我无法获取数据.我的代码目前看起来像这样:

 findMember = browser.find_elements_by_xpath("//div[contains(@class, '_instance _personInstance _volunteer')]")对于 findMember 中的元素:使用 open('names.csv', 'w') 作为 n:n.write(element.find_element_by_xpath("//div[@data-id]") + ',' + element.find_element_by_xpath("//div[@data-name]"))

没有错误消息 - 但也没有创建文件.

你能帮我吗?

解决方案

这需要一段时间,但现在我在 Satheesh 的帮助下找到了我的问题的解决方案 答案:

findMember = browser.find_elements_by_xpath("//div[contains(@class, '_instance _personInstance _volunteer')]")使用 open('names.csv', 'w') 作为 n:对于 findMember 中的元素:n.write(element.get_attribute('data-id') + ', ' + element.get_attribute('data-name') + '\n')

谢谢:-)

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?

解决方案

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 :-)

这篇关于Python Selenium 将数据 ID 和数据名称保存在文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
Python最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆