AttributeError:“设置”对象没有属性“超时”

时间:2020-01-22 05:42:36

标签: python python-3.x beautifulsoup

我在代码方面遇到一些问题,请帮助我。

我使用此功能删除了页面中的所有链接:

def get_links(link):
    soup = BeautifulSoup(link, 'lxml')
    block = soup.find('div', class_='block-top-important')
    projects = [] 
    for string in block.find_all('a', class_='post-preview-text post-preview-text--no-padding'):
        #print(string)
        projects.append ({
            string.get('href')
        })
    return(projects)

但是,当我在第二个func中发送这些链接以抓取页面时,它会在字符串4中返回错误:

def parse(html):
    stranica = []
    for link in html:
        soup = BeautifulSoup(urllib.request.urlopen(link), 'lxml')
        page = soup.find(class_= 'fb-quotable')
        title = page.find('h1').text
        for main_text in page:
            main_text.text = page.find('p', class_='align-left')
        stranica.append ((title, main_text))

我的主要功能,它以代码形式发送链接:

def main():
    url = 'https://www.nur.kz/'
    op = get_html(url)
    take_links = get_links(op)
    start_parse = parse(take_links)


if __name__ == '__main__':
        main()

完整错误跟踪:

Traceback (most recent call last):
  File "C:\Users\admin\AppData\Roaming\Sublime Text 3\Local\New pars.py", line 66, in <module>
    main()
  File "C:\Users\admin\AppData\Roaming\Sublime Text 3\Local\New pars.py", line 62, in main
    start_parse = parse(take_links)
  File "C:\Users\admin\AppData\Roaming\Sublime Text 3\Local\New pars.py", line 47, in parse
    soup = BeautifulSoup(urllib.request.urlopen(link), 'lxml')
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 515, in open
    req.timeout = timeout
AttributeError: 'set' object has no attribute 'timeout'
[Finished in 4.4s]

1 个答案:

答案 0 :(得分:0)

好吧,如果有人遇到相同的问题,我就决定了我的问题:

错误在这里:

        projects.append ({
            string.get('href')
        })

我的“ for”使用“ {}”中的链接,因此这就是为什么它们是“设置”对象而不是“字符串”并且urllib返回错误的原因。

我如何修复它:

projects.append (string.get('href'))