我试图从这个网站的第4和第5表的特定列拉数据https://hollowknight.fandom.com/wiki/Damage_Values_and_Enemy_Health_(Hollow_Knight)
这是我的代码
import bs4
import requests
url = "https://hollowknight.fandom.com/wiki/Damage_Values_and_Enemy_Health_(Hollow_Knight)"
req = requests.get(url)
soup = bs4.BeautifulSoup(req.text, "html.parser")
names = []
number = []
for row in rows[1:]:
names.append(row.find_all('td')[0])
number.append(row.find_all('td')[1])
for first, second in zip(names, number):
print(first.text, second.text)
由于某种原因,它看不到第4或第5个表。但是,如果我替换
中的3table = soup.find_all('table')[3]
如果值为2或更低,它就能看到。谁能帮我理解一下为什么网站上看不到最后两张表?
要获得特定的列,可以使用nth-of-type()
CSS选择器。
为了使用CSS选择器,使用.select()
方法而不是.find_all()
。
这会找到"标准敌人"以及"老板和小老板";当只选择<;健康&;列:
standard_enemy_health = soup.select(
"table:nth-of-type(4) tr:nth-of-type(n+3) td:nth-of-type(6)"
)
bosses_health = soup.select("table:nth-of-type(5) tr:nth-of-type(n+3) td:nth-of-type(4)")
首先df
返回为标准敌人,df1
返回为boss和迷你boss,您可以直接使用pd.read_html
作为传递数据,它将返回为DataFrame
import pandas as pd
main_data=soup.find_all("table")[3]
df=pd.read_html(str(main_data))[0]
main_data=soup.find_all("table")[4]
df1=pd.read_html(str(main_data))[0]