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
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']
没加单引号