鍍金池/ 問答/Python  HTML/ python3 url讀取

python3 url讀取

import urllib.request,urllib.parse,urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

urlname = input('Enter URL:')
count=input('Enter count:')
pos=input('Enter position:')
count=int(count)
pos=int(pos)
urls=list()

for times in range(count+1):
    print('Retrieving:', urlname)
    respon = urllib.request.urlopen(urlname, context=ctx)
    html = respon.read()
    soup = BeautifulSoup(html, 'html.parser')
    tags = soup('a')
    for tag in tags:
        urls.append(tag.get('href',None))
    urlname=urls[pos-1]
    

本意是輸入一個URL,然后讀取該URL下的第pos個URL,重復該行為count次。
在循環(huán)體里面,urlname雖然變了,但是respon = urllib.request.urlopen(urlname, context=ctx)似乎并沒有受到影響。。嘗試每次都適用close()來關閉也沒變化。。。是不是我的理解有問題。。麻煩各位大大幫忙看下。。。初學者。。有點懵。。

回答
編輯回答
淺時光

你的pos變量有變過嗎?pos不變,urls[pos-1]也不會變,因為urls是向后追加元素,前幾個元素還是不變的。

2017年6月23日 15:30