【发布时间】:2013-07-22 04:10:05
【问题描述】:
我正在尝试解析 HTML 文件(demo.html 以使所有相对链接成为绝对链接。这是我尝试在 Python 脚本中执行此操作的方法 -
from bs4 import BeautifulSoup
f = open('demo.html', 'r')
html_text = f.read()
f.close()
soup = BeautifulSoup(html_text)
for a in soup.findAll('a'):
for x in a.attrs:
if x == 'href':
temp = a[x]
a[x] = "http://www.esplanade.com.sg" + temp
for a in soup.findAll('link'):
for x in a.attrs:
if x == 'href':
temp = a[x]
a[x] = "http://www.esplanade.com.sg" + temp
for a in soup.findAll('script'):
for x in a.attrs:
if x == 'src':
temp = a[x]
a[x] = "http://www.esplanade.com.sg" + temp
f = open("demo_result.html", "w")
f.write(soup.prettify().encode("utf-8"))
但是,输出文件demo_result.html 包含许多意外更改。例如,
<script type="text/javascript" src="/scripts/ddtabmenu.js" />
/***********************************************
* DD Tab Menu script- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* + Drop Down/ Overlapping Content-
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
</script>
更改为
<script src="http://www.esplanade.com.sg/scripts/ddtabmenu.js" type="text/javascript">
</script>
</head>
<body>
<p>
/***********************************************
* DD Tab Menu script- (c) Dynamic Drive DHTML code library (www.dynamicdrive.com)
* + Drop Down/ Overlapping Content-
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
谁能告诉我哪里出错了?
感谢和最热烈的问候。
【问题讨论】:
-
我的工作正常。
-
@user1471175 - 你是什么意思?它是否只转换链接而不像我在问题中提到的那样更改 HTML 的其他部分?
-
对不起,我正在寻找错误的错误 :)
标签: python html hyperlink beautifulsoup web-crawler