I am really new in Python, so I'm facing this issue:
#!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')
I am getting this error : AttributeError: 'NoneType' object has no attribute 'encode'
Any helps, please?
<a>that does not have anhrefattribute, which meanslink.get("href" + '\n')returnsNone, andNonedoesn't have anencode()method. - g.d.d.cNone, likelist.reverse, or (b) you called some function that usually returns a value but returnsNonewhen there is no value to get, like manyfind-type functions. - abarnertfile.write(href.encode())line, so it's eitherfileorhrefthat'sNone. Since the error message is aboutencoderather thanwrite, it must behref. So now, you just need to figure out what function you called to gethref. If you don't understand why that function can returnNone, read the docs, and it'll probably explain. So then you just have to figure out what to do with those cases. - abarnert