python - 使用python从url中提取标题
问题描述
我想用来urllib
从下面的 html 文档中提取标题。我在下面提供了开始部分:
html_doc = """
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>Three Little Pigs</title>
<meta name="generator" content="Amaya, see http://www.w3.org/Amaya/">
</head>
<body>
我使用urlopen
过,urllib.request
但似乎url
html 文档中的类型不允许我提取任何内容。
我努力了:
from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_title():
soup = urlopen(html_doc)
print(soup.title.string)
get_title()
我得到了以下结果:
ValueError: unknown url type: '!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\n "http://www.w3.org/TR/html4/loose.dtd">\n<html>\n<head>\n <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">\n <title>Three Little Pigs</title>\n <meta name="generator" content="Amaya, see http://www.w3.org/Amaya/">\n</head>\n\n<body'
任何人都可以帮助解决这个问题吗?
解决方案
html_doc
不是URL
,它是实际的源代码字符串,您可以使用BeautifulSoup
'shtml.parser
对其进行解析,然后从中提取标题:
from bs4 import BeautifulSoup
def get_title():
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.title.string)
get_title()
输出:
Three Little Pigs
推荐阅读
- azure - 使用文件流压缩文件并上传到 Azure Blobstorage
- powershell - powershell 脚本在 100 台计算机上重新启动服务
- c# - UdpListener、Webhook 和 HttpListener
- google-places-api - Google Places API 自动完成,如何添加第二个地址
- amazon-web-services - 如何将新的策略定义或 ADMX 文件导入 AWS 托管的 Active Directory?
- sql-server-2008 - In Case 声明更新日期不超过今天
- python - python csv进行计算时如何避免无穷大
- mongodb - 使用 MongoDB 构建数据的建议
- spring-boot - Spring Cloud Config 通过 Vault 和 Git 解析秘密属性
- python - 如何在不使用numpy的情况下将两个数组中的公共元素复制到一个新数组中