2013-01-24 2 views
0

하나의 URL에서 작업중인 텍스트 스크레이퍼가 있습니다. 문제는 25 개의 URL을 다 써야한다는 것입니다. 이 URL은 거의 동일하며, 유일한 차이는 마지막 문자입니다. 다음은 좀 더 명확한 코드입니다.목록에서 URL을 사용하여 텍스트 스크랩하기 (BeautifulSoup4)

import urllib2 
from bs4 import BeautifulSoup 

f = open('(path to file)/names', 'a') 
links = ['http://guardsmanbob.com/media/playlist.php?char='+ chr(i) for i in range(97,123)] 

response = urllib2.urlopen(links[0]).read() 
soup = BeautifulSoup(response) 

for tr in soup.findAll('tr'): 
    if not tr.find('td'): continue 
    for td in tr.find('td').findAll('a'): 
     f.write(td.contents[0] + '\n') 

목록에서 한 번에 모든 URL을 실행하도록이 스크립트를 만들 수 없습니다. 내가 관리 할 수 ​​있었던 모든 것은 각 URL의 첫 번째 노래 이름입니다. 미안해, 내 영어로. 날 이해 해주길 바래.

답변

1

I can't make this script to run all urls from list in one time.

이 하나 개의 매개 변수, *args와 방법에 코드를 저장 (또는 무엇이든 당신이 원하는 이름, 바로 *을 잊지 마세요). *은 목록을 자동으로 언팩합니다. *의 정식 명칭은 없지만 일부 사람들 (나 포함)은 splat operator이라고 부릅니다.

def start_download(*args): 
    for value in args: 
     ##for debugging purposes 
     ##print value 

     response = urllib2.urlopen(value).read() 
     ##put the rest of your code here 

if __name__ == '__main__': 
    links = ['http://guardsmanbob.com/media/playlist.php?char='+ 
       chr(i) for i in range(97,123)] 

    start_download(links) 

편집 :가 아니면 링크의 목록을 통해 바로 바로 루프와 각을 다운로드 할 수 있습니다.

links = ['http://guardsmanbob.com/media/playlist.php?char='+ 
       chr(i) for i in range(97,123)] 
    for link in links: 
     response = urllib2.urlopen(link).read() 
     ##put the rest of your code here 

편집 2 : 여기

import urllib2 from bs4 import BeautifulSoup, SoupStrainer links = ['http://guardsmanbob.com/media/playlist.php?char='+ chr(i) for i in range(97,123)] for link in links: response = urllib2.urlopen(link).read() ## gets all <a> tags soup = BeautifulSoup(response, parse_only=SoupStrainer('a')) ## unnecessary link texts to be removed not_included = ['News', 'FAQ', 'Stream', 'Chat', 'Media', 'League of Legends', 'Forum', 'Latest', 'Wallpapers', 'Links', 'Playlist', 'Sessions', 'BobRadio', 'All', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Misc', 'Play', 'Learn more about me', 'Chat info', 'Boblights', 'Music Playlist', 'Official Facebook', 'Latest Music Played', 'Muppets - Closing Theme', 'Billy Joel - The River Of Dreams', 'Manic Street Preachers - If You Tolerate This Your Children Will Be Next', 'The Bravery - An Honest Mistake', 'The Black Keys - Strange Times', 'View whole playlist', 'View latest sessions', 'Referral Link', 'Donate to BoB', 'Guardsman Bob', 'Website template', 'Arcsin'] ## create a file named "test.txt" ## write to file and close afterwards with open("test.txt", 'w') as output: for hyperlink in soup: if hyperlink.text: if hyperlink.text not in not_included: ##print hyperlink.text output.write("%s\n" % hyperlink.text.encode('utf-8')) 

test.txt에 저장된 출력의 모든 링크를 받고 다음 파일에 저장을위한

, 여기에 특정 주석이있는 전체 코드입니다 :

enter image description here

test.txt을 이전 파일을 덮어 쓰기 때문에 링크 목록을 반복 할 때마다 다른 파일 이름 (예 : 노래 제목)으로 변경하는 것이 좋습니다.

+0

첫 번째 방법을 사용하는 동안 나는 이것을 얻습니다 : AttributeError : 'list'객체에는 'timeout'속성이 없습니다. 두 번째 방법을 사용하는 동안 각 URL의 첫 번째 노래 이름 만 표시됩니다. 어떻게 해결할 수 있습니까? – user1628593

+0

그래, 두 번째 방법을 사용하여 링크 목록을 반복 할 수있었습니다. 그런 다음 각 URL의 노래 이름을 모두 가져오고 싶습니다. 맞습니까? –

+0

네, 맞습니다. – user1628593

관련 문제