python - 連結網址輸出的問題
仅有的幸福
仅有的幸福 2017-05-24 11:35:29
0
2
724
import requests
res=requests.get('http://news.sina.com.cn/china/')
res.encoding="utf-8"

from bs4 import BeautifulSoup
soup=BeautifulSoup(res.text,'html.parser')
a=soup.select('a')
for i in a:
    print (i[href])

我想要輸出每個連結的網址,但是上面的程式碼 結果是
錯誤:print (i[href])
NameError: name 'href' is not defined

仅有的幸福
仅有的幸福

全部回覆(2)
巴扎黑

首先字典的 key 需要引號, print(i['href'])

你可以用 print(i.get('href') ,防止找不到这个元素的时候报 KeyError

https://docs.python.org/3/lib...

仅有的幸福
import requests
from bs4 import BeautifulSoup


res = requests.get('http://news.sina.com.cn/china/')
res.encoding = "utf-8"

soup = BeautifulSoup(res.text, 'html.parser')
a = soup.select('a')
for i in a:
    try:
        href = i['href']
        if 'http' in href:
            print(href)
    except KeyError:
        continue

給個建議:問問題的時候盡量把自己的疑問說出來。你這裡主要是 i['href'] 沒加單引號

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!