为什么AttributeError:'bytes'对象没有属性'findAll'

问题描述 投票:0回答:1

我正在尝试从趋势页面中删除youtube数据。出现错误

from bs4 import BeautifulSoup
import requests
import csv

source = requests.get("https://www.youtube.com/feed/trending").text
soup = BeautifulSoup(source, 'lxml').encode("utf-8")

csv_file = open('YouTube.csv','w')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Title', 'Description'])

for content in soup.findAll('div', class_= "yt-lockup-content"):
#for content in soup.find_all('div', class_= "yt-lockup-content"):
    print (content)
python xpath beautifulsoup findall
1个回答
1
投票

AttributeError:'bytes'对象没有属性'findAll'是因为在您的代码中您正在执行:

soup = BeautifulSoup(source, 'lxml').encode("utf-8")

正在发生的事情是,您正在通过编码字符串将str转换为byteencode用于使用选择的编码将str转换为bytes

一个绝对不要在程序内部使用bytes进行操作。而是使用unicode sandwitch原理。在读取时将bytes转换为str,对str进行处理,然后在写入时将str转换为bytes到输出。

所以只需在程序内部使用str,而不要使用bytes

soup = BeautifulSoup(source, 'lxml')
© www.soinside.com 2019 - 2024. All rights reserved.