我已经使用Python获取了网页的HTML,现在我想要查找所有链接到标题中的.CSS文件。我尝试分区,如下所示,但运行时发生错误“IndexError:字符串索引超出范围”,并将它们各自保存为自己的变量(我知道如何执行此操作)。如何在使用python的文本块中找到文件名?
sytle = src.partition(".css")
style = style[0].partition('<link href=')
print style[2]
c =1
我不认为这是正确的方法来解决这个问题,所以会喜欢一些建议。提前谢谢了。以下是我需要从中提取.CSS文件的那种文本部分。
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
<!--[if gte IE 7]><!-->
<link href="/stylesheets/master.css?1342791430" media="screen, projection" rel="stylesheet" type="text/css" />
<link href="/stylesheets/adapt.css?1342791413" media="screen, projection" rel="stylesheet" type="text/css" />
<!-- <![endif]-->
<link href="/stylesheets/print.css?1342791421" media="print" rel="stylesheet" type="text/css" />
<link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon-precomposed" />
<link href="http://dribbble.com/shots/popular.rss" rel="alternate" title="RSS" type="application/rss+xml" />
你已经接受了一个答案,似乎有一些奇怪的原因upvotes。使用正则表达式来解析HTML只是丑陋,容易出错,容易中断和不灵活。您应该使用适当的HTML解析器来处理HTML数据[lxml.html,BeautifulSoup等...)HTML是结构化数据,它不仅仅是“文本” – 2012-07-26 22:14:20