为什么这段代码报错articles = str(tree.xpath('//div[contains(@class,"text")]//ext()')[0]) article_str = html.etree.tostring(articles, encoding='utf-8', method='html').decode('utf-8'),报错为: 'lxml.etree._ElementUnicodeResult' cannot be serialized
时间: 2023-12-14 19:03:03 浏览: 37
这个错误是因为 `articles` 是一个 `lxml.etree._ElementUnicodeResult` 对象,而 `html.etree.tostring()` 方法只接受 `Element` 对象作为参数,不能处理 `ElementUnicodeResult` 对象。
为了解决这个问题,您可以尝试直接使用 `articles` 对象,而不是先将其转换为字符串再转换为 `Element` 对象。具体地,您可以尝试以下代码:
```python
articles = tree.xpath('//div[contains(@class,"text")]//text()')
article_str = ''.join(articles)
```
这里使用 `//text()` 选择器来获取 `<div>` 标签内的所有文本,然后通过 `join()` 方法将它们连接成一个字符串。这样得到的 `article_str` 对象就可以被序列化了。
如果您需要保留 HTML 标记,可以尝试以下代码:
```python
articles = tree.xpath('//div[contains(@class,"text")]/*')
article_str = ''.join(html.etree.tostring(e, encoding='unicode') for e in articles)
```
这里使用 `*` 选择器来获取 `<div>` 标签内的所有子元素,然后通过 `html.etree.tostring()` 方法将它们序列化为字符串,并使用 `join()` 方法将它们连接成一个字符串。注意,这里需要将 `encoding` 参数设置为 `unicode`,以便保留 HTML 标记。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)