我从youtube上获取(搜索)数据的程序出现错误,并且显示错误AttributeError:'function'对象没有属性'read'我在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") ```
答案 0 :(得分:1)
您是否尝试过使用请求库?
像这样:
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")
答案 1 :(得分:0)
这里已经犯了错误:
response = urllib.request.urlopen
html = response.read()
您将urllib.request.urlopen
放入response
变量中,而不是调用该函数的结果。
所以不是
response = urllib.request.urlopen
您应该使用适当的参数来调用它:
response = urllib.request.urlopen( .. parameters come here ... )