Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/90.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用xpath和lxml将div的所有内容解析为列表中的1个元素而不是多个元素_Python_Html_Parsing_Xpath_Lxml - Fatal编程技术网

Python 如何使用xpath和lxml将div的所有内容解析为列表中的1个元素而不是多个元素

Python 如何使用xpath和lxml将div的所有内容解析为列表中的1个元素而不是多个元素,python,html,parsing,xpath,lxml,Python,Html,Parsing,Xpath,Lxml,我在一个网站上有多个div,其中包含一类文本,如下所示: <div class="text"> "test1" <br> "test2" <br> "test3" <br> </div> 我得到: ['test1', 'test2', 'test3'] 但我真的想: ['test1\ntest2\test3'] 我可以接受有或没有换行符,因为我可以去掉它们。我想一定有办法用xpath实现这一点。否则,我想我将不得不使用i

我在一个网站上有多个div,其中包含一类文本,如下所示:

<div class="text">
"test1"
<br>
"test2"
<br>
"test3"
<br>
</div>
我得到:

['test1', 'test2', 'test3']
但我真的想:

['test1\ntest2\test3']     

我可以接受有或没有换行符,因为我可以去掉它们。我想一定有办法用xpath实现这一点。否则,我想我将不得不使用iterparse()?

我建议您在Python中加入结果

mytext = tree.xpath('//*[@class="text"]/text()')
print('\n'.join(mytext))
或者,您可以在xpath表达式中应用函数,例如,规范化空间,将为您提供一个字符串,但您仍然需要将换行符放入字符串中

tree.xpath('normalize-space(//*[@class="text"])')
-> '"test1""test2""test3"'

我建议您使用Python加入结果

mytext = tree.xpath('//*[@class="text"]/text()')
print('\n'.join(mytext))
或者,您可以在xpath表达式中应用函数,例如,规范化空间,将为您提供一个字符串,但您仍然需要将换行符放入字符串中

tree.xpath('normalize-space(//*[@class="text"])')
-> '"test1""test2""test3"'

它可以帮助您获取div中的文本,而不是通过以下方式检索的

    //*[@class="text"]/text()[preceding-sibling::br]
从技术上讲,在
br
标记之间意味着:

 //*[@class="text"]/text()[preceding-sibling::br and following-sibling::br]

它可以帮助您获取div中的文本,而不是通过以下方式检索的

    //*[@class="text"]/text()[preceding-sibling::br]
从技术上讲,在
br
标记之间意味着:

 //*[@class="text"]/text()[preceding-sibling::br and following-sibling::br]

请你把全部代码发一次好吗?请你把全部代码发一次好吗