2017-02-20 8 views
0

파이썬에서 나는 URL 목록에서이를 반환하는 프로그램을 가지고 있습니다. 그들 중 일부는 그들이 내가 텍스트 파일에 두 개의 URL을로드 예를 들어 목록<title> 태그를 반환하고 싶습니다. <title> 잘못된 요청 <.title> 파이썬 3

에 함께 넣어되고있어 잘못된 요청을 반환

는 :

http://www.scientific.net/MSF 
http://www.scientific.net/JMNM 

는 반환 :

<title>Bad Request</title> 
<title>Journal of Metastable and Nanocrystalline Materials</title> 

목록에 첫 번째 URL 만있는 경우 코드가 올바르게 작동합니다. 어떻게하면 나쁜 요청 대신 두 제목을 모두 검색하게합니까?

내 코드 :

url_list= [] 

f = open('test.txt','r') #text file with url 
for line in f: 
    url_list.append(line) 

for link in url_list: 
    try: 
     r = requests.get(link) 
     soup = BeautifulSoup(r.content,"html.parser") 
     title = soup.title 
     title.string = title.get_text(strip = True) 
     print(str(title)) 

    except: 
     print("No Title Found ") 
     continue 

답변

1

텍스트 파일을 읽는 중 문제가 발생합니다. for link in url_list 루프에서 link의 첫 번째 값은 http://www.scientific.net/MSF\n이되며 결국 \nBad Request 오류가 발생합니다. 읽는 동안 행에서 \n을 제거하면 코드가 작동합니다. 마지막 줄에는 \n이 없으므로 간단히 url_list.append(line[:-1])을 사용하면 마지막 줄에 실패합니다.

0
r = requests.get(link) 
    soup = BeautifulSoup(r.content,"html.parser") 
    #title = soup.title 
    titles = soup.find_all('title') 
    for title in titles: 
     title.string = title.get_text(strip = True) 
     print(str(title)) 

..find()에 대한 바로 가기, 그것은 첫 번째 일치를 반환합니다, 당신은 모든 matchs을 반환 find_all()를 사용해야합니다.

관련 문제