2017-02-13 104 views
0

尝试读取URL列表,然后在课堂上输出html。它的作品,但只为列表中的最后一个网址,我似乎无法弄清楚为什么。我设置了超时等,但它仍然只是返回和空的响应,除了最后一个网址。Python从文件中读取URL只会获取最后一个URL

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

from bs4 import BeautifulSoup 

import requests 
import time 

with open('/Users/usrname/Desktop/links.txt') as f: 
    for line in f: 
     print(line) 
     html_doc = requests.get(line, verify=False, timeout=2) 
     soup = BeautifulSoup(html_doc.text, 'html.parser') 
     #time.sleep(1.3) # seconds   
     print (soup.find_all("div", "location-content"))   

回答

3

该文件的最后一行没有回车,而其他行没有回车,而其他行都不是有效的URL。你需要剥离回车带rstrip()

for line in f: 
    line = line.rstrip() 
+0

完美..干杯 – Kravitz

+0

不客气! –