2

有一个名为“name.txt”的文件
内容如下

<td>    
    <input class="name" value="Michael">    
    <input class="age" value="22">    
    <input class="location" value="hebei">

</td>


<td>
    <input class="name" value="Jack">
    <input class="age" value="23">
    <input class="location" value="NewYo">
</td>

现在我想使用pyquery获取所有输入标签,然后遍历输入标签

使用 '.filter' 获取所有姓名等级和年龄等级

最后,获取姓名和年龄的值,并将所有结果写入一个名为“name_file.txt”的文件中

我的代码如下

# -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
doc = pq(filename='name.txt')

input = doc('input')

for result in input.items():
    name_result = result.filter('.name')
    age_result = result.filter('.age')
    name = name_result.attr('value')
    age = age_result.attr('value')
    print "%s:%s" %(name,age)
    c = "%s:%s" %(name,age)
    f = file('name_file.txt','w')
    f.write(c) 
    f.close()

但是现在,我遇到了2个问题

1. 我得到的结果不是“Michael:22”,而是“Michael:None”和“None:22”

2.我写入的'name_file'的内容只是'None:None',并不是我得到的所有结果。

4

2 回答 2

2

第一个问题源于您循环遍历所有<input ... >元素(由 收集doc('input')),因此您只能获得名称或年龄,但不能同时获得两者。您可以做的是遍历各个<td> ... </td>块并提取匹配的孩子 - 有点浪费,但要符合您的想法:

from pyquery import PyQuery as pq

doc = pq(filename='name.txt')  # open our document from `name.txt` file

for result in doc('td').items():  # loop through all <td> ... </td> items
    name_result = result.find('.name')  # grab a tag with class="name"
    age_result = result.find('.age')  # grab a tag with class="age"
    name = name_result.attr('value')  # get the name's `value` attribute value
    age = age_result.attr('value')  # get the age's `value` attribute value
    print("{}:{}".format(name, age))  # print it to the STDOUT as name:age

至于第二部分-您name_file.txt以写入模式打开文件,写入一行然后在每个循环中关闭它-当您以写入模式打开文件时,它将截断其中的所有内容,因此您继续为每个文件编写第一行环形。尝试这样做:

from pyquery import PyQuery as pq

doc = pq(filename='name.txt')  # open our document from `name.txt` file

with open("name_file.txt", "w") as f:  # open name_file.txt for writing
    for result in doc('td').items():  # loop through all <td> ... </td> items
        name_result = result.find('.name')  # grab a tag with class="name"
        age_result = result.find('.age')  # grab a tag with class="age"
        name = name_result.attr('value')  # get the name's `value` attribute value
        age = age_result.attr('value')  # get the age's `value` attribute value
        print("{}:{}".format(name, age))  # print values to the STDOUT as name:age
        f.write("{}:{}\n".format(name, age))  # write to the file as name:age + a new line 
于 2017-07-08T05:02:42.230 回答
0
from pyquery import PyQuery as pq
doc = pq(filename = 'text.txt')

input=doc.children('body')

f = file('name_file.txt', 'w')

for x in [result.html() for result in input.items('td')]:
    x=pq(x)
    name = x('input').eq(0).attr('value')
    age = x('input').eq(1).attr('value')
    print "%s:%s" % (name, age)
    c = "%s:%s" % (name, age)
    f.write(c)

f.close()

您不能在循环中使用文件打开语句,否则您只会在每次循环迭代中只用一条记录覆盖文件。

同样,您在循环之后关闭它,而不是在插入每条记录之后。

于 2017-07-08T05:26:59.063 回答