2017-01-02 59 views
1

我有以下腳本可以獲取用戶名網頁的公共數據。我目前正在爲一個用戶名工作。從文本文件中輸入多個用戶名以在Python腳本中運行

usernames = ['johnsmith'] 

r = requests.get('https://url/'+username) 
html = r.text.encode("utf-8") 
text = html[html.index("htmlclass = ")+21:] 
text = (text[:text.index("};</script>")]+"}").replace('\\"', "") 
dictionary = loads(text) 

我想從txt文件(data.txt)中提取多個用​​戶名並同時運行它。我能夠將文本從txt文件轉換成列表。

# Usernames extracted from text file: 
base = [line.rstrip() for line in open('data.txt')] 

示例文本TXT文件:

janedoe 
johnnyb 
marcusx 
taylors 

但我不知道如何調整我的腳本接受多個用戶名。我怎麼做?

回答

0

把你當前的代碼在功能和運行功能,每個用戶名在base使用列表中,也就是說,一個列表理解:

def get_username_data(username): 
    r = requests.get('https://url/'+username) 
    html = r.text.encode("utf-8") 
    text = html[html.index("htmlclass = ")+21:] 
    text = (text[:text.index("};</script>")]+"}").replace('\\"', "") 
    return loads(text) 

result = [get_username_data(uname) for uname in base] 
相關問題