python中的一個用法不清楚
問題描述
在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)
相關文章:
1. javascript - 百度echarts series數據更新問題2. mysql - 一個表和多個表是多對多的關系,該怎么設計3. python - type函數問題4. php - 第三方支付平臺在很短時間內多次異步通知,訂單多次確認收款5. Mysql && Redis 并發問題6. css3 - css before 中文亂碼?7. mysql新建字段時 timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 報錯8. css3 - 手機網頁中用css寫1px的描邊,為什么需要加一句overflow:hidden才能真正顯示1px?9. javascript - node服務端渲染的困惑10. css - 求推薦幾款好用的移動端頁面布局調試工具呢?
