Home  >  Q&A  >  body text

python - Problem with link URL output

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

仅有的幸福仅有的幸福2705 days ago725

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑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...

    reply
    0
  • 仅有的幸福

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

    reply
    0
  • Cancelreply