我想用BeautifulSoup学习python,但是';str';对象没有属性';查找所有';发生错误

我想用BeautifulSoup学习python,但是';str';对象没有属性';查找所有';发生错误,python,Python,我想在python中使用BeautifulSoup,但是'str'对象没有'find_all'属性,因此发生了错误。 预期的结果是 为数组中的每个值分配数字 这是我的密码 import requests from bs4 import BeautifulSoup url = "https://ja.wikipedia.org/wiki/メインページ" response= requests.get(url) soup = BeautifulSoup(response.con

我想在python中使用BeautifulSoup,但是'str'对象没有'find_all'属性,因此发生了错误。 预期的结果是 为数组中的每个值分配数字

这是我的密码

import requests
from bs4 import BeautifulSoup

url = "https://ja.wikipedia.org/wiki/メインページ"

response= requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
today = soup.find("div", attrs={"id": "on_this_day"}).text

entries = today.find_all("li")
today_list = []
index = 1

for entry in entries:
    today_list.append([index, entry.get_text()])
    index += 1
print(today_list)
错误消息

AttributeError                            Traceback (most recent call last)
<ipython-input-10-c70240e5052b> in <module>
     8 today = soup.find("div", attrs={"id": "on_this_day"}).text
     9 
     ---> 10 entries = today.find_all("li")
    11 today_list = []
    12 index = 1

AttributeError: 'str' object has no attribute 'find_all'
AttributeError回溯(最近一次调用)
在里面
8 today=soup.find(“div”,attrs={“id”:“on\u this\u day”})
9
--->10个条目=今天。查找所有(“li”)
11今天的清单=[]
12指数=1
AttributeError:“str”对象没有“find_all”属性

您能帮忙吗?

删除
今日
变量上的
.text
,该变量会删除html

保留此选项将启用
.findall
方法来提取所有
  • 标记

    import requests
    from bs4 import BeautifulSoup
    
    url = "https://ja.wikipedia.org/wiki/メインページ"
    
    response= requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    today = soup.find("div", attrs={"id": "on_this_day"})
    
    entries = today.find_all("li")
    today_list = []
    index = 1
    
    for entry in entries:
        today_list.append([index, entry.get_text()])
        index += 1
    print(today_list)
    
    返回

    [[1, '天武天皇が日本で初めて肉食・狩猟を禁じる詔を発する(675年 - 天武天皇4年4月17日))'], [2, 'フランドル伯ボードゥアン9世がラテン帝国の初代皇帝に即位(1204年)'], [3, 'スコッ
    トランドの元女王メアリーがイングランドに亡命(1568年)'], [4, '松尾芭蕉、北へ向けて江戸を出立。『奥の細道』の旅へ(1689年 - 元禄2年3月27日)'], [5, 'ローマ教皇ベネディクトゥス15世がジャンヌ・ダルクを列聖(1920年)'], [6, '第1回アカデミー賞授賞式(1929年)'], [7, '東京、大阪、名古屋の3証券取引所が取引再開(1949年)'], [8, '韓国で5・16軍事クーデター(1961年)'], [9, '田部井淳子ら日本女子登山隊が女性初のエベレスト登頂に成功(1975年)'], [10, 'ヒマラヤ山脈のシッキム王国が、国民投票の結果に基づきインドに合併される(1975年)'], [11, '初の実用的なパーソナルコンピュータ「Apple II」が発売(1977年)'], [12, 'オウム真理教教祖・麻原彰晃を逮捕(1995年)']]
    

    错误消息说明了一切

    AttributeError: 'str' object has no attribute 'find_all'
    
    所以您试图获取某个str对象的find_all()属性。很明显,有一个字符串对象不应该是字符串

    你注意到了吗

    today = soup.find("div", attrs={"id": "on_this_day"}).text
    
    today = soup.find("div", attrs={"id": "on_this_day"}).text
    
    这里有一个
    .text
    ,它使它成为一个字符串,所以如果你不希望它成为一个字符串,你只需删除它,这就是你的解决方案