【问题标题】:AttributeError: 'set' object has no attribute 'timeout'AttributeError:“set”对象没有属性“timeout”
【发布时间】:2020-01-22 05:42:36
【问题描述】:

我的代码有些问题,请帮助我。

我用这个函数从页面中获取了所有链接:

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)

但是当我在 2nd 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]

【问题讨论】:

  • 能否提供完整的错误跟踪信息?
  • 好的,我添加了它

标签: python python-3.x beautifulsoup


【解决方案1】:

好的,我决定了我的问题,如果有人有同样的问题:

错误在这里:

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

我的“for”在“{}”中获取链接,所以这就是为什么它们是“set”对象,而不是“string”并且 urllib 返回错误。

我是如何解决的:

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

【讨论】:

    猜你喜欢
    • 2018-03-11
    • 2015-11-14
    • 1970-01-01
    • 2021-08-09
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多