[英]Cleaning HTML using python
我有以下代碼,但是我收到錯誤。 我正在嘗試從Tag1和Tag2之間的html文件中獲取文本,而沒有for循環,代碼正在工作(對於一個文件),但是在目錄中循環時卻沒有
from bs4 import BeautifulSoup
from urllib import urlopen
import os
import bleach
import re
rootdir = mydirectory
for subdir, dirs, files in os.walk(rootdir):
for file in files:
url = file
print url
raw = urlopen(url).read()
type(raw)
Tag1 = raw.find("""<div class="song-text">""")
Tag2 = raw.rfind("""<div style="text-align:center;padding-bottom:10px;">""")
Cleaned = raw[Tag1+23:Tag2]
print Cleaned
錯誤消息:追溯(最近一次呼叫最近):文件“ TestClean.py”,行12,原始= urlopen(url).read()文件“ /usr/lib/python2.7/urllib.py”,行87 ,在urlopen中返回opener.open(url)文件“ /usr/lib/python2.7/urllib.py”,第208行,在open中返回getattr(self,name)(url)文件“ / usr / lib / python2。 7 / urllib.py“,第463行,在open_file中返回self.open_local_file(url)文件,” / usr / lib / python2.7 / urllib.py“,第477行,在open_local_file中,引發IOError(e.errno,e.strerror ,例如e.filename)IOError:[Errno 2]沒有這樣的文件或目錄:'paroles-a-beautiful-lie.html'
錯誤消息表明缺少文件。 os.walk
僅返回文件名,而不返回文件的完整路徑。 1)取path = os.path.join(subdir, file)
2)讀取文件open(path).read()
而不使用urlopen
從Traceback很清楚,它無法找到“ paroles-a-beautiful-lie.html”文件。 我建議你一步一步走。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.