Heim  >  Fragen und Antworten  >  Hauptteil

python – Problem mit der Link-URL-Ausgabe

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])

Ich möchte die URL jedes Links ausgeben, aber der obige Code führt zu
Fehler: print (i[href])
NameFehler: Name 'href' ist nicht definiert

仅有的幸福仅有的幸福2705 Tage vor715

Antworte allen(2)Ich werde antworten

  • 巴扎黑

    巴扎黑2017-05-24 11:37:29

    首先字典的 key 需要引号, print(i['href'])

    你可以用 print(i.get('href') ,防止找不到这个元素的时候报 KeyError

    https://docs.python.org/3/lib...

    Antwort
    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
    

    给个建议:问问题的时候尽量把自己的疑问说出来。你这里主要是 i['href'] 没加单引号

    Antwort
    0
  • StornierenAntwort