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

标签 python beautifulsoup

如果元素有 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/

相关文章:

python - 当javascript生成一些html时获取html源

python - 查找与 Beautiful Soup 的特定链接

python - BS4 : Getting text in tag

Python,将所有链接、标题和正文文本附加到一个数组或 json 文件中

python - Python cProfile 中的严重开销?

python - 使用python从网页中提取所有链接

python - C:初始化二叉堆

python - 使用 BeautifulSoup 解析网页上的表格

python - Python 中星期日 = 0 的星期常量

python - 发送电子邮件后尝试将电子邮件主题和日期时间打印到txt文件