URL을 가져 와서 텍스트를 구문 분석 한 다음 위젯을 검색하는 코드 스 니펫이 있습니다. 위젯을 감지하는 방법은 단어 widget1
을 찾은 다음 위젯의 끝을 나타내는 endwidget
을 찾습니다.파일에 쓰고 이상한 들여 쓰기 받기
기본적으로 코드는 단어 widget1
을 찾고 endwidget
으로 끝나면 텍스트의 모든 줄을 파일에 씁니다. 그러나 내 코드 첫 번째 widget1
줄 뒤에 모든 줄 들여 쓰기입니다. 왜이 들여 쓰기를 얻고있다
widget1 this is a really cool widget
it does x, y and z
and also a, b and c
endwidget
:
이 내가이 원하는 것은 내 출력
widget1 this is a really cool widget
it does x, y and z
and also a, b and c
endwidget
입니까? 이
for url in urls:
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
text= soup.prettify()
texts = soup.findAll(text=True)
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
# If the parent of your element is any of those ignore it
return False
elif re.match('<!--.*-->', str(element)):
# If the element matches an html tag, ignore it
return False
else:
# Otherwise, return True as these are the elements we need
return True
visible_texts = filter(visible, texts)
inwidget=0
# open a file for write
for line in visible_texts:
# if line doesn't contain .widget1 then ignore it
if ".widget1" in line and inwidget==0:
match = re.search(r'\.widget1 (\w+)', line)
line = line.split (".widget1")[1]
# make the next word after .widget1 the name of the file
filename = "%s" % match.group(1) + ".txt"
textfile = open (filename, 'w+b')
textfile.write("source:" + url + "\n\n")
textfile.write(".widget1" + line)
inwidget = 1
elif inwidget == 1 and ".endwidget" not in line:
print line
textfile.write(line)
elif ".endwidget" in line and inwidget == 1:
textfile.write(line)
inwidget= 0
else:
pass
감사합니다.''는'texts' 변수이거나 각각'visible_texts의 줄'입니까 – user1328021
또한 정확히 무엇을하고 있습니까? 그것은 캐리지 리턴을 제거하고 그 밖의 무엇입니까? – user1328021
\ n을 사용하여 각 줄마다 문자열 목록을 만든 다음 각 줄을 제거합니다. 즉, 처음과 마지막에 공백을 제거하지만 줄 바꿈 만하면 해당 줄을 지울 수 있습니다. lstrip로 시작) 문자열은 \ n을 구분 기호로 사용하여 다시 결합됩니다. – LtWorf