AttributeError:' NoneType'对象没有属性'编码使用beautifulsoup

时间:2018-03-09 23:43:29

标签: python beautifulsoup attributeerror nonetype

我是Python的新手,所以我面对这个问题:

#!venv/bin/python
import sys
import requests
import bs4

if len(sys.argv) == 3:
# If arguments are satisfied store them in readable variables
   url = 'http://%s' % sys.argv[1]
   file_name = sys.argv[2]

print('Grabbing the page...')
# Get url from command line
response = requests.get(url)
response.raise_for_status()

# Retrieve all links on the page
soup = bs4.BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')

file = open(file_name, 'wb')
print('Collecting the links...')
for link in links:
    href = link.get("href") + '\n' 
    file.write(href.encode())
file.close()
print('Saved to %s' % file_name)

else:

print('Usage: ./collect_links.py www.example.com file.txt')

我收到此错误:AttributeError:' NoneType'对象没有属性'编码'

有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

解决了!

我包含这一行:  href =" {0} \ n" .format(link.get(" href"))

谢谢你们,伙计们!