使用Beautiful Soup分离HTML和Javascript和CSS的Web抓取

时间:2014-07-23 13:43:05

标签: python web-scraping beautifulsoup

我正在尝试抓取一个包含Javascript,CSS和HTML的网页。现在这个网页也有一些文字。当我在运行soup.get_text()命令时使用文件处理程序打开网页时,我只想查看HTML部分而不是其他内容。有可能这样做吗?

目前的源代码是:

from bs4 import BeautifulSoup

soup=BeautifulSoup(open("/home/Desktop/try.html"))

print soup.get_text()

如果只更改网页中的HTML部分而不进行其他操作,我该如何更改?

2 个答案:

答案 0 :(得分:0)

尝试删除包含不需要的文本(或样式属性)的标记内容。

这是一些代码(在基本情况下测试)

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("/home/Desktop/try.html"))

# Clear every script tag
for tag in soup.find_all('script'):
    tag.clear()

# Clear every style tag
for tag in soup.find_all('style'):
    tag.clear()

# Remove style attributes (if needed)
for tag in soup.find_all(style=True):
    del tag['style']

print soup.get_text()

答案 1 :(得分:0)

这取决于 get 的含义。 Dmralev的答案将清除其他标签,这将正常工作。但是,<HTML>soup中的标记,因此

print soup.html.get_text()
假设部分意味着HTML与代码的其余部分分开(即其他代码不在<HTML>标记内),

也可以使用更少的行。