通过Python字符串替换从多个.html文件中删除所有内部链接
我想从一堆 .html 文件中删除所有内部链接。简单来说,任何以 <a href=
开头的东西都是链接,如果它不以 <a href="http
开头,那就是内部链接。
我正在尝试写一个小的 Python 脚本来实现这个功能。现在每个文件的前半部分都能完美处理,但在同一个链接上总是崩溃。我当然检查过有没有拼写错误或者漏掉的 </a>
标签,但我没有发现。如果我重新运行这个脚本,那个“问题链接”会被删除,但它的 </a>
标签却留在那儿。似乎每次重新运行脚本都会删除更多的链接,但我希望能一次性把所有内部链接都删掉。
有没有人能给我建议我哪里做错了?请看下面我使用的代码。
tList = [r"D:\@work\projects_2013\@websites\pythonforspss\a44\@select-variables-having-pattern-in-names.html"]
for path in tList:
readFil = open(path,"r")
writeFil = open(path[:path.rfind("\\") +1] + "@" + path[path.rfind("\\") + 1:],"w")
flag = 0
for line in readFil:
for ind in range(len(line)):
if flag == 0:
try:
if line[ind:ind + 8].lower() == '<a href=' and line[ind:ind + 13].lower() != '<a href="http':
flag = 1
sLine = line[ind:]
link = sLine[:sLine.find(">") + 1]
line = line.replace(link,"")
print link
except:
pass
if flag == 1:
try:
if line[ind:ind + 4].lower() == '</a>':
flag = 0
line = line.replace('</a>',"")
print "</a>"
except:
pass
writeFil.write(line)
readFil.close()
writeFil.close()
2 个回答
0
query = input('Enter the word to be searched:')
url = 'https://google.com/search?q=' + query
request_result = req.get(url).text
soup = BS(request_result, 'lxml')
for link in soup.find_all('a', href= re.compile("https://")):
print(link['href'].replace("/url?q=",""))
我在使用Beautiful Soup的时候,用了上面的代码,成功只提取出了https链接。
我试过上面提到的解决方案,但对我来说并没有效果,实际上我用上面的代码后,链接数量大幅减少。
希望这对你有帮助!
1
使用像 BeautifulSoup 或 lxml 这样的HTML解析器。使用 lxml 的话,你可以这样做:
import lxml.html as LH
url = 'http://stackoverflow.com/q/15186769/190597'
doc = LH.parse(url)
# Save a copy of the original just to compare with the altered version, below
with open('/tmp/orig.html', 'w') as f:
f.write(LH.tostring(doc))
for atag in doc.xpath('//a[not(starts-with(@href,"http"))]'):
parent = atag.getparent()
parent.remove(atag)
with open('/tmp/altered.html', 'w') as f:
f.write(LH.tostring(doc))
在 BeautifulSoup 中,效果是这样的:
import bs4 as bs
import urllib2
url = 'http://stackoverflow.com/q/15186769/190597'
soup = bs.BeautifulSoup(urllib2.urlopen(url))
with open('/tmp/orig.html', 'w') as f:
f.write(str(soup))
for atag in soup.find_all('a', {'href':True}):
if not atag['href'].startswith('http'):
atag.extract()
with open('/tmp/altered.html', 'w') as f:
f.write(str(soup))