[英]Trying to get data with BeautifulSoup
我试图找到一种从网站获取温度数据的方法。 不管我做什么,我都会得到None作为输出。
这是我使用的代码
import urllib.request
from bs4 import BeautifulSoup
contenturl = "http://www.awebsite.com/"
soup = BeautifulSoup(urllib.request.urlopen(contenturl).read())
table = soup.find('table')
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
text = ''.join(td.find(text=True))
print (text+"|"),
print ()
我一直在BS 3中使用BS。不胜感激。
要获取温度,请在表格行中找到文字“ Temperature”:
import re
temperature_row = soup.find(text=re.compile('Temperature')).find_parent('tr')
temperature = temperature_row.find_all('td')[-1].get_text()
演示:
>>> temperature_row = soup.find(text=re.compile('Temperature')).find_parent('tr')
>>> temperature_row.find_all('td')[-1].get_text()
'85.9°F\n'
要获取所有温度数据,我将开始查找带有“当前天气”文本的标题; 它包装在<big>
标记中(ick,已弃用的HTML标记),然后使用以下两个单元格处理所有行:
row = soup.find('big', text=re.compile('Current\s*Weather')).find_parent('tr')
while True:
row = row.find_next_sibling('tr')
cells = row.find_all('td')
if len(cells) != 2:
break
label, value = (cell.get_text().strip() for cell in cells)
print(label, value, sep=': ')
这将产生:
>>> row = soup.find('big', text=re.compile('Current\s*Weather')).find_parent('tr')
>>> while True:
... row = row.find_next_sibling('tr')
... cells = row.find_all('td')
... if len(cells) != 2:
... break
... label, value = (cell.get_text().strip() for cell in cells)
... print(label, value, sep=': ')
...
Temperature: 85.9°F
Humidity: 50%
Dewpoint: 65.1°F
Wind: ESE at 7.0 mph
Barometer: 27.346 in & Falling Slowly
Today's Rain: 0.00 in
Yearly Rain: 11.49 in
Wind Chill: 85.4°F
THW Index: 87.6°F
Heat Index: 88.1°F
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.