python - 使用 beautifulsoup 和 python 删除某些标签

标签 python html beautifulsoup strip

问题

我正在尝试从 BeautifulSoup 下载的 html 文件中删除 <h2><div class=...> 等样式标签。我确实想保留标签包含的内容(如文本) 然而,这似乎不起作用。

我尝试过的

for url in urls:
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.content, 'html.parser')
    table = soup.find("div", {"class": "product_specifications bottom_l js_readmore_content"})
    print "<hr style='border-width:5px;'>"
    for style in table.find_all('style'):
        if 'style' in style.attrs:
            del style.attrs['style']
    print table

我尝试使用的网址

Python HTML parsing with beautiful soup and filtering stop words

Remove class attribute from HTML using Python and lxml

BeautifulSoup Tag Removal

最佳答案

您可以使用分解(): http://www.crummy.com/software/BeautifulSoup/bs4/doc/#decompose

如果您只想清除文本或将元素从树中移除,请使用clearextract(分解上面的描述)。

关于python - 使用 beautifulsoup 和 python 删除某些标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26233315/

相关文章:

Python为什么无法读取包含内容的文件?

python - 使用Python抓取谷歌搜索结果标题和网址

python - 如何抓取两个具有相同类名的表?

python - 合并月份和年份列以创建日期列

python - Django 文件 uploader 抛出错误 "cannot pickle ' _io.BufferedRandom' object"同时使用 celery 上传更多感谢 2.5mb 的图像

python - 为什么我的变量在列表中的行为不符合我的预期?

html - 在 CSS : caption box doesn't resize according to image size 中编码的悬停预览

html - 表格宽度不起作用,向左移动太远

html - 具有线性渐变的三 Angular 形中的 CSS 颜色过渡

python - 如何在 Python 中使用 Beautifulsoup 仅打印文本?