简体   繁体   中英

Beautiful Soup Get Attribute Error

Getting an error : "linkdetail = link.get('href') AttributeError: 'NoneType' object has no attribute 'get'" in the following script.

If I run it with the commented lines instead of the last two it grabs the correct element.

from bs4 import BeautifulSoup

import sys

import os.path

for i in os.listdir(os.getcwd()):
    soup = BeautifulSoup(open(i))
    link_list = []
    soup.prettify().encode('UTF-8')
    link = soup.find(class_="attribute-url")
    ## link_list.append(link)
    ## print link_list
    linkdetail = link.get('href')
    print linkdetail

Any help appreciated, I'm stuck.

Try doing this -

    links = soup.findAll('a')
    for link in links:
        linkdetail = link.get('href')
        print linkdetail

Try doing this:

    links = soup.findAll(class_="attribute-url")
    for link in links:
        print link.text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM