您的位置:首頁技術文章
文章詳情頁

python中的一個用法不清楚

瀏覽:100日期:2022-07-03 14:47:59

問題描述

在python編寫爬蟲的過程中(爬取wiki百科的詞條),使用迭代器輸出過程中出現了url['href']想著應該屬于迭代器里面一個用法,但卻沒有找到,求助這個用法的意思,謝謝

#coding:utf-8import urllibimport urllib2import refrom bs4 import BeautifulSoupresp = urllib2.urlopen('https://en.wikipedia.org/wiki/Main_Page').read()soup = BeautifulSoup(resp,'html.parser')listurl = soup.findAll(’a’,href=re.compile('^/wiki/'))for url in listurl:print url.get_text(),'------>','https://en.wikipedia.org'+url['href']

最后一行的url['href'],對爬取得數據產生了截斷的效果,沒加之前,輸出為:print url輸出:Disclaimers加了之后,輸出為:print url['href']輸出:/wiki/Wikipedia:General_disclaimer求解,謝謝

問題解答

回答1:

只要實現了__getitem__方法的類就可以使用中括號取值。

In [16]: class A(): ...: def __getitem__(self,a): ...: return a ...: In [17]: a = A() In [18]: a[’a’], a[1] Out[18]: (’a’, 1)

標簽: Python 編程
相關文章:
国产综合久久一区二区三区