【发布时间】: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-python、http://stackoverflow.com/questions/1936466/beautifulsoup-grab-visible-webpage-text 和 http://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) 并处理这些网址,摆脱timeouts、status_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