python - 如何删除 "baca"或从html中读取?

标签 python beautifulsoup

我成功创建了一个简单的程序来抓取 url 并将提取的 html 翻译成英语。然而,对于这个特定的网站(下面的链接),“html.find_all('p')”还会提取嵌入 anchor 标记的不需要的“p”标记。

示例 1:我不想要的 HTML

<p>Baca: <a href="https://nasional.tempo.co/read/1216929/soenarko-sarankan-kivlan-zen-berhati-hati-omongan-diviralkan">Soenarko Sarankan Kivlan Zen Berhati-hati Omongan Diviralkan</a></p>

示例 2:我想要的 HTML

<p>"Ya, jadi penangguhan penahanan ini, pertama kami memang mengajukan penangguhan penahanan," kata Ferry membuka sesi wawancara. Hari itu, Mabes Polri telah mengabulkan penanggungan penahanan terhadap Soenarko yang menjadi tersangka kepemilikan senjata ilegal.</p>

有没有一种方法可以让代码过滤掉示例 1,只保留示例 2?

link = "https://nasional.tempo.co/read/1216914/moeldoko-penangguhan-penahanan-soenarko-bisa-diterima"

webpage_response = requests.get(link)
webpage = webpage_response.content
page = BeautifulSoup(webpage, "html.parser")

html_title = page.find("title")
title2 = html_title.get_text()
title = title2.strip("- Bisnis Tempo.co")

html = page.find(attrs={"itemprop": "articleBody"})
text = html.find_all("p")

最佳答案

提供 if 条件来检查是否有任何“Baca”文本并跳过它。

from bs4 import BeautifulSoup
import requests
link = "https://nasional.tempo.co/read/1216914/moeldoko-penangguhan-penahanan-soenarko-bisa-diterima"

webpage_response = requests.get(link)
webpage = webpage_response.content
page = BeautifulSoup(webpage, "html.parser")

html_title = page.find("title")
title2 = html_title.get_text()
title = title2.strip("- Bisnis Tempo.co")

html = page.find(attrs={"itemprop": "articleBody"})
items = html.find_all("p")

for item in items:
    if not ('Baca' in item.text):
        print(item)
<小时/>

或者您可以使用 decompose() 函数来删除。

from bs4 import BeautifulSoup
import requests
link = "https://nasional.tempo.co/read/1216914/moeldoko-penangguhan-penahanan-soenarko-bisa-diterima"

webpage_response = requests.get(link)
webpage = webpage_response.content
page = BeautifulSoup(webpage, "html.parser")

html_title = page.find("title")
title2 = html_title.get_text()
title = title2.strip("- Bisnis Tempo.co")

html = page.find(attrs={"itemprop": "articleBody"})
items = html.find_all("p")

for item in items:
    if 'Baca' in item.text:
        item.decompose()

print(items)

关于python - 如何删除 "baca"或从html中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724491/

相关文章:

python - 在 Python 中将 HTML 子标签更改为同级标签

Python理解巩固

python - 如何在 Python 中将变量传入和传出函数

python - 在我的网页抓取程序中提取第一个和最后一个页码时如何修复 "List index out of range"错误?

python - BeautifulSoup 能否保留 CDATA 部分?

python - 用 beautifulsoup 解析 css 选择器

python - 使用 BeautifulSoup 查找关键字的子字符串

python - 使用 pandas 或 Numpy 根据列数据选择一系列行

python - PyBrain 弃用警告

python - 如何用循环缩短这个网格移动逻辑(python)