我在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
根据您的变量名,我假设您正在寻找提取“lufttemperatureinc”/“Aktuell”值。在
如果您查看您的错误,您可以看到数组索引(10)超出范围-这可能是因为BeautifulGroup处理CSS selectors in version 4.7的方式发生了变化,或者可能是由于页面的更改。在
总之,你可以通过改变一点代码来获得你想要的值。不是寻找第10个TD,而是查找第4个TR下的TDs,您将得到一个包含用于LuftTemperature行的TDs的数组:
或者
^{pr2}$我想这会返回一个空列表。在
'td:nth-of-type(10)'
我想意思是“选择父元素的第十个元素”。 现在,td的父项是tr,所以tr中只有4个tdsoup.select('td')[0]
给了你想要的?在相关问题 更多 >
编程相关推荐