I'm getting an error for a program that fetches(searches) data from youtube , and it shows an error AttributeError: 'function' object has no attribute 'read' i am on python3

import urllib.request
from bs4 import BeautifulSoup
import sys

flag = 0
textToSearch = 'hello world'
query = sys.argv[0].strip("\"").replace(" ","+")
url = "https://www.youtube.com/results?search_query=" + query

response = urllib.request.urlopen
html = response.read()

soup = BeautifulSoup(html,"lxml")
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
    flag = 1
print ('https://www.youtube.com' + vid['href'])
if flag == 0:
    print ("No results found") ```

2 Answers

0
quantummind On Best Solutions

The mistake has been made here:

response = urllib.request.urlopen
html = response.read()

You put urllib.request.urlopen into response variable instead of the result of calling that function.

So instead of

response = urllib.request.urlopen

you should call it with appropriate parameters:

response = urllib.request.urlopen( .. parameters come here ... )
1
Klemen Koleša On

have you tried using requests library ?

like this:

import requests
from bs4 import BeautifulSoup
import sys

flag = 0
textToSearch = 'hello world'
query = sys.argv[0].strip("\"").replace(" ","+")
url = "https://www.youtube.com/results?search_query=" + query

response = requests.get(url)
html = response.content

soup = BeautifulSoup(html,"lxml")
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
    if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
        flag = 1
    print ('https://www.youtube.com' + vid['href'])
    if flag == 0:
        print ("No results found")