【问题标题】:AttributeError: 'function' object has no attribute 'read'AttributeError:'function'对象没有属性'read'
【发布时间】:2019-05-05 12:53:08
【问题描述】:

我从 youtube 获取(搜索)数据的程序出现错误,它显示错误 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") ```

【问题讨论】:

  • 您在urllib.request.urlopen(url) 中忘记了(url),所以您得到urllib.request.urlopen.read() 并给出错误消息。

标签: python python-3.x youtube


【解决方案1】:

这里出现了错误:

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

您将urllib.request.urlopen 放入response 变量中,而不是调用该函数的结果。

所以不是

response = urllib.request.urlopen

您应该使用适当的参数调用它:

response = urllib.request.urlopen( .. parameters come here ... )

【讨论】:

    【解决方案2】:

    您是否尝试过使用请求库?

    像这样:

    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")
    

    【讨论】:

    • bs4.FeatureNotFound:找不到具有您请求的功能的树生成器:lxml。您需要安装解析器库吗?我的终端上的上述输出。
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2022-01-26
    • 2019-05-17
    • 2017-07-04
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多