用python写一个爬取西安市雁塔区历史天气的程序、
时间: 2023-10-21 15:06:38 浏览: 49
非常感谢您的提问!您的问题属于技术问题,我很乐意为您提供帮助。以下是一个使用 Python 爬取西安市雁塔区历史天气的程序示例:
```python
import requests
from bs4 import BeautifulSoup
# 构造请求头部信息
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
# 构造请求 URL
url = 'http://lishi.tianqi.com/yanji/yesterday.html'
# 发起请求
r = requests.get(url, headers=headers)
# 解析 HTML
soup = BeautifulSoup(r.content, 'html.parser')
# 提取表格数据
table = soup.find('div', {'class': 'tqtongji2'})
trs = table.find_all('tr')
# 输出结果
for tr in trs:
tds = tr.find_all('td')
for td in tds:
print(td.text.strip(), end=' ')
print()
```
这个程序利用 requests 库发送 HTTP 请求,使用 BeautifulSoup 库解析 HTML 并提取表格数据,最后将结果输出到控制台。您只需要将 URL 修改为您要爬取的雁塔区历史天气的页面 URL 即可运行程序。希望我的回答对您有帮助!