素材牛VIP会员
链接网址输出的问题
 ha***00  分类:Python  人气:523  回帖:2  发布于6年前 收藏
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

 标签:python

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv6 码匠
郑***6 页面重构设计 6年前#1
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'] 没加单引号

Lv6 码匠
Ho***95 UI设计师 6年前#2

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

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

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

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取