如何在靓汤4.7.1中使用“选择”?

2024-10-01 13:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在beauthulsoup4.6中使用了这个代码。因为版本4.7.1,这个代码显示了一个错误。在

有人能帮我在新版本中如何使用“select”吗?在

import json
from urllib.request import urlopen
from bs4 import BeautifulSoup

url= 'http://www.nordhessen-wetter.de'
u = urlopen(url)
soup = BeautifulSoup(u, 'html.parser')

lufttemperatur = soup.select('td:nth-of-type(10)')[0].text

以下是错误消息:

Traceback (most recent call last): File "main.py", line 9, in lufttemperatur = soup.select('td:nth-of-type(10)')[0].text IndexError: list index out of range

live version of this code on repl.it


Tags: of代码fromimport版本urltype错误
2条回答

根据您的变量名,我假设您正在寻找提取“lufttemperatureinc”/“Aktuell”值。在

如果您查看您的错误,您可以看到数组索引(10)超出范围-这可能是因为BeautifulGroup处理CSS selectors in version 4.7的方式发生了变化,或者可能是由于页面的更改。在

总之,你可以通过改变一点代码来获得你想要的值。不是寻找第10个TD,而是查找第4个TR下的TDs,您将得到一个包含用于LuftTemperature行的TDs的数组:

lufttemperatur = soup.select("tr:nth-of-type(4) > td") # array of TDs

或者

^{pr2}$
lufttemperatur = soup.select('td:nth-of-type(10)')[0]

我想这会返回一个空列表。在

'td:nth-of-type(10)'我想意思是“选择父元素的第十个元素”。 现在,td的父项是tr,所以tr中只有4个td

soup.select('td')[0]给了你想要的?在

相关问题 更多 >