使用Python进行天气的爬虫
时间: 2024-02-16 10:53:27 浏览: 23
可以使用Python中的requests库和BeautifulSoup库来进行天气的爬取。
首先,需要确定要爬取的天气网站,以中国天气网(http://www.weather.com.cn/)为例。
然后,可以使用requests库来获取网页内容:
```python
import requests
url = "http://www.weather.com.cn/weather/101010100.shtml" # 北京市天气预报网址
response = requests.get(url)
html = response.content.decode("utf-8") # 将网页内容转换为utf-8编码的字符串
```
接着,可以使用BeautifulSoup库来解析网页内容,获取所需要的天气信息:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser") # 使用BeautifulSoup解析网页内容
weather = soup.find(class_="wea").string # 获取当前天气状况
temperature = soup.find(class_="tem").text.strip() # 获取当前气温
```
最后,将获取的天气信息打印出来即可:
```python
print("当前天气:", weather)
print("当前气温:", temperature)
```
完整代码:
```python
import requests
from bs4 import BeautifulSoup
url = "http://www.weather.com.cn/weather/101010100.shtml"
response = requests.get(url)
html = response.content.decode("utf-8")
soup = BeautifulSoup(html, "html.parser")
weather = soup.find(class_="wea").string
temperature = soup.find(class_="tem").text.strip()
print("当前天气:", weather)
print("当前气温:", temperature)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)