2016-07-09 132 views
-2

我想我想變成一個列表是一個字符串。將字符串轉換成列表

所以當我運行它打印出一個網址列表。我希望把這些網址到像這樣的列表:

["Apple", "Pear", "Radio"] 

代碼:

url = "http://www.wired.com/category/science/page/" 
a = list(range(1, 12)) 
i=0 


while i < len(a): 
    urls1 = url + str(i) 
    print urls1[1] 
    i+=1 

我想要做的:(我想,如果我結合他們兩個,我可以得到網址去與刮刀)

import urllib 
import re 


urls = [urls1] 
#https://www.wired.com/2016/07/google-tests-new-crypto-chrome-fend-off-quantum-attacks/ 
i=0 

regex = '<h2 class="title brandon clamp-5">(.+?)</h2>' 

#https?:(\/\/www\.wired\.com\/2016(\/[A-Za-z0-9\-\._~:\/\?#\[\]@!$&'\(\)\*\+,;\=]*)?) 

pattern = re.compile(regex) 

while i < len(urls): 
    htmlfile = urllib.urlopen(urls[i]) 
    htmltext = htmlfile.read() 
    titles = re.findall(pattern, htmltext) 



    for elem in titles: 
     print elem 

    i+=1 
+0

所以你想要一個網址列表?網址從哪裏來?什麼是'urls1'? –

+0

@MoonCheesez我最初想到的是將兩者結合起來,這就是爲什麼urls1處於最底層的原因。這些網址最初在一個列表中。 – user5544792

+0

@MoonCheesez我想製作一個網址列表,然後在這個網址中使用這些網址 – user5544792

回答

0

要獲得11頁的URL列表:

url = "http://www.wired.com/category/science/page/" 
urls = [] 
for i in range(1, 12): 
    new_url = url + str(i) 
    urls.append(new_url) 
print urls 
+0

'map(「http://www.wired.com/category/science/page/ {}」.format,range(1 ,12))'或'[url + str(i)for i in range(1,12)]'' –