當我決議超過 1 個類時,我在第 12 行得到一個錯誤(當我將所有添加到 find 時)錯誤:ResultSet 物件沒有屬性“find”。您可能將元素串列視為單個元素
import requests
from bs4 import BeautifulSoup
heroes_page_list=[]
url = f'https://dota2.fandom.com/wiki/Dota_2_Wiki'
q = requests.get(url)
result = q.content
soup = BeautifulSoup(result, 'lxml')
heroes = soup.find_all('div', class_= 'heroentry').find('a')
for hero in heroes:
hero_url = heroes.get('href')
heroes_page_list.append("https://dota2.fandom.com" hero_url)
# print(heroes_page_list)
with open ('heroes_page_list.txt', "w") as file:
for line in heroes_page_list:
file.write(f'{line}\n')
uj5u.com熱心網友回復:
您正在您需要這樣做的標簽a串列中搜索標簽,div
heroes = soup.find_all('div', class_= 'heroentry')
a_tags = [hero.find('a') for hero in heroes]
for a_tag in a_tags:
hero_url = a_tag.get('href')
heroes_page_list.append("https://dota2.fandom.com" hero_url)
heroes_page_list看起來像這樣
['https://dota2.fandom.com/wiki/Abaddon',
'https://dota2.fandom.com/wiki/Alchemist',
'https://dota2.fandom.com/wiki/Axe',
'https://dota2.fandom.com/wiki/Beastmaster',
'https://dota2.fandom.com/wiki/Brewmaster',
'https://dota2.fandom.com/wiki/Bristleback',
'https://dota2.fandom.com/wiki/Centaur_Warrunner',
....
uj5u.com熱心網友回復:
錯誤是說明您需要做的一切。
find()方法只能在單個元素上使用。find_all()回傳一個元素串列。您正在嘗試應用于find()a listof 元素。
如果你想申請find('a'),你應該申請類似的東西:
heroes = soup.find_all('div', class_= 'heroentry')
for hero in heroes:
hero_a_tag = hero.find('a')
hero_url = hero_a_tag .get('href')
heroes_page_list.append("https://dota2.fandom.com" hero_url)
您基本上必須對該find()方法生成的串列中的每個元素應用該find_all()方法
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525828.html
上一篇:使用正則運算式在Python字串中查找電子郵件地址和其他值
下一篇:R決議字串以提取、計算和替換數字
