python - 链接网址输出的问题
仅有的幸福
仅有的幸福 2017-05-24 11:35:29
0
2
719
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学习者快速成长!