【问题标题】:Beautifulsoup get rid of embedded js and css in htmlBeautifulsoup 摆脱 html 中嵌入的 js 和 css
【发布时间】:2017-02-12 00:25:59
【问题描述】:

我需要通过requests.get()解析多个html。我只需要保留页面的内容并摆脱嵌入的 javascript 和 css。我看到了以下帖子,但没有解决方案适合我。 http://stackoverflow.com/questions/14344476/how-to-strip-entire-html-css-and-js-code-or-tags-from-html-page-in-pythonhttp://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-texthttp://stackoverflow.com/questions/2081586/web-scraping-with-python

我得到了一个不剥离 js 或 css 的工作代码...这是我的代码...

count = 1
for link in clean_urls[:2]:
    page = requests.get(link, timeout=5)
    try:
        page = BeautifulSoup(page.content, 'html.parser').text
        webpage_out = open(my_params['q'] + '_' + str(count) + '.txt', 'w')
        webpage_out.write(clean_page)
        count += 1
    except:
        pass


webpage_out.close()

我尝试包含上述链接中的解决方案,但没有代码适合我。 哪行代码可以摆脱嵌入式js和嵌入式css

2016 年 10 月 4 日问题更新

read.csv的文件是这样的……

trump,clinton
data science, operating system
windows,linux
diabetes,cancer

我当时用这些术语访问了 gigablast.com 以搜索一行。一次搜索将是trump clinton。结果是一个 url 列表。我requests.get(url) 并处理这些网址,摆脱timeoutsstatus_code = 400s,并建立一个干净的clean_urls = [] 列表。之后我触发以下代码...

count = 1
for link in clean_urls[:2]:
    page = requests.get(link, timeout=5)
    try:
        page = BeautifulSoup(page.content, 'html.parser').text
        webpage_out = open(my_params['q'] + '_' + str(count) + '.txt', 'w')
        webpage_out.write(clean_page)
        count += 1
    except:
        pass


webpage_out.close()

在这行代码page = BeautifulSoup(page.content, 'html.parser').text 我有整个网页的文本,包括嵌入的样式和脚本。我不能用 BeautifulSoup 来定位它们,因为标签不再存在。我确实尝试了page = BeautifulSoup(page.content, 'html.parser')find_all('<script>') 并尝试摆脱脚本,但我最终删除了整个文件。期望的结果将是 html 的所有文本,没有任何...

body {
    font: something;
}

或任何 javascript...

$(document).ready(function(){
    $some code
)};

最终文件应该没有任何代码,只有文档的内容。

【问题讨论】:

  • 您能否提供具有输入和所需输出的可重现样本?谢谢。
  • 我要更新问题了。

标签: python-3.x beautifulsoup html-parser


【解决方案1】:

我在 scraping HTML 页面

时使用此代码摆脱了 javascript 和 CSS 代码
import requests
from bs4 import BeautifulSoup

url = 'https://corporate.walmart.com/our-story/our-business'
r = requests.get(url)
html_doc = r.text

soup = BeautifulSoup(html_doc, 'html.parser')
title =  soup.title.string

for script in soup(["script", "style"]):
    script.decompose()    

with open('output_file.txt', "a") as text_file:
    text_file.write("\nURL : "+ url)
    text_file.write("\nTitle : " + title)
    
               
    for p_tag_data in soup.find_all('p'):
        text_file.write("\n"+p_tag_data.text)
        
    for li_tag_data in soup.find_all('li'):
        text_file.write("\n"+li_tag_data.text)
        
    for div_tag_data in soup.find_all('div'):
        text_file.write("\n"+div_tag_data.text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2016-02-04
    • 2021-03-20
    • 2019-06-16
    相关资源
    最近更新 更多