Python 正在尝试使用BeautifulSoup获取数据

Python 正在尝试使用BeautifulSoup获取数据,python,beautifulsoup,Python,Beautifulsoup,我试图找到一种从网站上获取温度数据的方法。无论我做什么,我都没有得到任何输出 这是我使用的代码 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.fin

我试图找到一种从网站上获取温度数据的方法。无论我做什么,我都没有得到任何输出

这是我使用的代码

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 ()

我在Python3中使用了BS。非常感谢您的帮助。

要获取温度,请在表格行中找到文本“温度”:

import re

temperature_row = soup.find(text=re.compile('Temperature')).find_parent('tr')
temperature = temperature_row.find_all('td')[-1].get_text()
演示:

为了获得所有的温度数据,我开始寻找带有“当前天气”文本的标题;它被包装在
标记(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

你能修复缩进吗?@MauroBaraldi:这是Python 3,对
urllib.request.urlopen()
的引用是完全正确的。哇。。。这确实奏效了。由于某种原因,我没有收到任何通知,我的问题得到了答案。所以我想出了一个相当“非正统”的方法。现在肯定会改变的。非常感谢。。。
>>> 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