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
巴扎黑2017-05-24 11:37:29
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...
仅有的幸福2017-05-24 11:37:29
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
A suggestion: When asking questions, try to express your doubts. What you mainly mean here is that you didn’t add single quotesi['href']