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])
I want to output the URL of each link, but the above code results in
Error: print (i[href])
NameError: name 'href' is not defined
First of all, the key of the dictionary needs quotes,
print(i['href'])
You can use
print(i.get('href')
,防止找不到这个元素的时候报KeyError
.https://docs.python.org/3/lib...
A suggestion: When asking questions, try to express your doubts. What you mainly mean here is that you didn’t add single quotes
i['href']