python - Problem with link URL output
仅有的幸福
仅有的幸福 2017-05-24 11:35:29
0
2
761
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

仅有的幸福
仅有的幸福

reply all(2)
巴扎黑

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...

仅有的幸福
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']

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template