首页 > 解决方案 > BeautifulSoup:在python中提取带有双引号的html元素的内容

问题描述

我想用 BeautifulSoup 从网站中提取元素的内容。以下是典型的相关 html 代码的样子:

<html>
<script for="document" event="onkeypress()" language="JScript"
type="text/jscript">
<!--
{
  if(window.event.shiftKey)
    javascript:window.print();
}
//-->
</script>

<head>

<title>Some title here</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<meta NAME="Generator" CONTENT="Some content here">
<meta NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<meta NAME="ROBOTS" CONTENT="NOARCHIVE">
<meta NAME="keywords" CONTENT=
"This is the important content~It is seperated by tilde~Information~Information"
>
<meta NAME="Ddate" CONTENT="">
<meta NAME="Makz" CONTENT="67">

在大多数情况下,它与以下代码完美配合:

soup = BeautifulSoup(fid, 'html')

important_infos = soup.find("meta", {"name":"keywords"})["content"]
splitted_infos = important_infos.split('~') 

但在某些情况下,我需要的信息有额外的引号,BeautifulSoup 只会在第二个引号出现之前捕获内容,然后简单地停止。所以我正在寻找的元素看起来像这样,例如:

<meta NAME="keywords" CONTENT="Info1~Info2~Company with an "Example Name"~Info4~Info5">

所以我只在“wth an”之前得到了contet,并且所有其他信息都不包括在内。

有没有办法解决这个问题,即使使用那些双引号,仍然可以从 CONTENT 中捕获所有信息?

标签: pythonhtmlbeautifulsoup

解决方案


推荐阅读