gpt4 book ai didi

python - 使用 Python BeautifulSoup 从网页中抓取没有 id 或类的元素

转载 作者:行者123 更新时间:2023-12-01 22:26:03 26 4
gpt4 key购买 nike

如果元素有 id 或 class,我知道如何从网页中抓取数据。

例如这里,soup 是一个 BeautifulSoup 对象。

for item in soup.findAll('a',{"class":"class_name"}):
title = item.string
print(title+"\n")

如果元素没有 id 或 class,我们怎么办?例如,没有 id 或 class 的段落元素。

或者在更糟糕的情况下,如果我们只需要像下面这样抓取一些纯文本会怎样?

<body>
<p>YO!</p>
hello world!!
</body>

例如,如何在上面的页面源代码中只打印 hello world!!?它没有 ID 或类。

最佳答案

如果你想定位一个没有定义 idclass 属性的元素:

soup.find("p", class_=False, id=False)

要在您的示例中找到像 hello world!! 这样的“文本”节点,您可以通过文本本身获取它 - 通过部分匹配或正则表达式匹配:

import re

soup.find(text=re.compile("^hello")) # find text starting with "hello"
soup.find(text="hello world!!") # find text with an exact "hello world!!" text
soup.find(text=lambda text: text and "!!" in text) # find text havin "!!" inside it

或者,您可以找到前面的 p 元素并获取 next text node :

soup.find("p", class_=False, id=False).find_next_sibling(text=True)
soup.find("p", text="YO!").find_next_sibling(text=True)

关于python - 使用 Python BeautifulSoup 从网页中抓取没有 id 或类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com