2016-01-08 79 views
-1

你好,我正在學習如何用BeautifulSoup解析HTML。我想知道是否可以使用用戶輸入一個for循環,因爲:用於Python的用戶輸入循環

for (user input) in A 

由於A是一個鏈接列表,使用戶可以選擇去一個鏈接,使用輸入。

然後我用urllib打開該鏈接並重復該過程。

+0

等待,您希望用戶從鏈接列表中選擇一個鏈接嗎?這不會通過for循環工作,因爲它只是遍歷元素。 –

+0

有一個鏈接列表,我希望用戶數字一個現在的位置,並與這個數字在那個位置打開鏈接 –

+0

那有什麼與解析HTML? – karlson

回答

0

您可以使用這樣的事情:

import urllib2 
from bs4 import BeautifulSoup 

choice = '' 
for url in urls: 
    print('Go to {}?'.format(url)) 
    decision = input('Y/n ') 
    if decision == 'Y': 
     choice = url 
     break 

if choice: 
    r = urllib2.urlopen(choice).read() 
    soup = BeautifulSoup(r, 'lxml') 
    # do something else 
0

這是不完全清楚我,如果你真的想要「開放」在瀏覽器中的鏈接,所以我包括一些代碼來做到這一點。這可能是你想要的「數位」嗎?

TL;博士

print("Which URL would you like to open?" 
    " (Please select an option between 1-{})".format(len(A))) 
for index, link in enumerate(A): 
    print index+1, link 

全:

from bs4 import BeautifulSoup 
import requests 
import webbrowser 


A = [ 
    'https://www.google.com', 
    'https://www.stackoverflow.com', 
    'https://www.xkcd.com', 
] 

print("Which URL would you like to open?" 
    " (Please select an option between 1-{})".format(len(A))) 
for index, link in enumerate(A): 
    print index+1, link 

_input = input() 

try: 
    option_index = int(_input) - 1 
except ValueError: 
    print "{} is not a valid choice.".format(_input) 
    raise 
try: 
    selection = A[option_index] 
except IndexError: 
    print "{} is not a valid choice.".format(_input) 
    raise 

webbrowser.open(selection) 
response = requests.get(selection) 
html_string = response.content 
# Do parsing... 
0

感謝您的幫助。我在這方面取得了解決方案。

創建兩個變量:count = input()postion = input()

我已經在使用循環計數:for _ in range(c) - 這個我可以做一個過程重複的次數,用戶想(這個assignement 4) 。

該位置(對於此分配在3上進行了預定義),我使用列表索引,列表中包含所有url。因此,對於開在3位的URL我:

url = links[p-1](-1該用戶輸入3,但列表索引從0(0,1,2 ......)

,然後啓動的原因我可以使用urllib.request.urlopen.read()