python - 美丽的汤 - 我们如何在元素之前获得元素?
问题描述
如果我有一个如下的html,并且我使用漂亮的汤来解析它,我如何访问<head>
元素之前的行。
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
例如,访问 head 元素的标准方法是soup.head
或者 body 是soup.body
. 我认为这是因为 head 和 body 都是标准标签。
有没有办法访问之前的元素<head>
?
解决方案
您可以通过选择 head 标签并遍历 previous_elements:
from bs4 import BeautifulSoup
from w3lib.html import remove_tags
html= '<?xml version="1.0" encoding="utf-8" standalone="no"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>'
soup= BeautifulSoup(html,"html.parser")
x= soup.head
while x.previous_element != None:
if not isinstance(x.previous_element, bs4.element.Tag):
p = x.previous_element.PREFIX + str(x.previous_element) +
x.previous_element.SUFFIX
prev_head = prev_head + p
else:
prev_head = str(x.previous_element) + prev_head
x = x.previous_element
prev_head = remove_tags(prev_head, which_ones= ("head",))
BeautifulSoup(prev_head)
在此过程之后,您将把上面<head>
的所有代码prev_head
作为一个字符串。然后BeautifulSoup(prev_head)
您可以获得一个 BS 对象以供以后使用。
PS:请注意,我删除了<head>
标签,因为<html>
它是第一个previous_element
. 我还格式化了非标记元素,因为它们的平面 str 格式不包括它们的前缀和后缀,使它们无法在 BS 对象中使用。
推荐阅读
- julia - 结合位置、关键字和默认参数并记录它们的 Julian 方法是什么?
- symfony - 使用访问控制拒绝返回访问
- html - translateY后如何摆脱div下方的空白
- json - 在 golang 中持久化嵌套结构
- javascript - 如何创建一个从 API 获取信息的接口?
- c++ - 用于容器和类型的模板函数以比较指针向量
- ios - 获取相对于 SKEffectNode 屏幕的绝对位置,因为它被 SKWarpGeometryGrid 扭曲
- python - 字典上的 For 循环给出超出范围的错误
- audio - 去除立体声电话录音中的低噪音回声
- c# - Unity 中的 DllNotFoundException,但在 Unity 之外正常工作