我正在尝试从网站获取天气信息并收集这些数据。但有些请求会返回空列表或与预期不同的信息。为什么会发生这种情况,从网站获取正确的 xpath 和信息的正确格式和方法是什么。
我尝试过使用多个网站,但无法始终如一地获得结果。
import requests
from lxml import html
site1data = requests.get('http://m.bom.gov.au/vic/melbourne/', verify =
False)
tree = html.fromstring(site1data.content)
humidity = tree.xpath('//div[@class="humidity"]/text()')
print(humidity)
预期的结果是这样的: 67% 但我得到了: ['\n\t\t\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t\t', '\n\t\t\t\t']
请您参考如下方法:
因为您要查找的文本数据显示在 <p> 中标记,不在 <div> 内本身:
<div class="humidity">
<h3>Humidity</h3>
<img class="humidity" src="/assets/images/ui/humidity.svg" />
<p>65%</p>
</div>
这个 xpath 应该可以解决您眼前的问题:
humidity = tree.xpath('//div[@class="humidity"]/p/text()')
