爬虫天气预报的c#代码
时间: 2023-12-19 12:32:12 浏览: 57
以下是一个简单的C#爬虫代码示例,用于爬取百度上的天气预报:
```csharp
using System;
using System.Net;
class Program
{
static void Main()
{
string cityPy = "beijing"; // 城市拼音
string historyUrl = "https://m.tianqi.com/lishi/"; // 爬取地址
string month = "202112"; // 月份
string url = $"{historyUrl}{cityPy}/{month}.html";
WebClient client = new WebClient();
string html = client.DownloadString(url);
Console.WriteLine(html);
}
}
```
这段代码使用了`WebClient`类来下载指定URL的HTML内容,并将其打印到控制台上。你可以根据自己的需求对代码进行进一步的扩展和优化。
相关问题
python爬虫天气预报
你可以使用 Python 的爬虫技术来获取天气预报数据。首先,你需要确定一个可靠的天气预报网站,例如中国气象网(http://www.weather.com.cn/)或者其他提供天气预报数据的网站。
然后,你可以使用 Python 的第三方库,例如 requests、BeautifulSoup等来发送网络请求并解析网页内容。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_weather(city):
url = f'http://www.weather.com.cn/weather/{city}.shtml'
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'}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
html = response.text
soup = BeautifulSoup(html, 'html.parser')
weather = soup.find(class_='wea').text
temperature = soup.find(class_='tem').text
return f'{city}的天气:{weather},温度:{temperature}'
city = '北京' # 你可
爬虫天气预报 XPATH
以下是使用XPath爬取天气预报的示例代码:
```python
import requests
from lxml import etree
# 设置请求头
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 = 'http://www.weather.com.cn/weather/101280101.shtml'
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
# 解析HTML
selector = etree.HTML(response.text)
# 获取天气信息
WeatherLink = selector.xpath('//*[@id="7d"]/ul/li')
WeatherList = []
for i in range(len(WeatherLink)):
date = WeatherLink[i].xpath('./h1/text()')[0]
weather = WeatherLink[i].xpath('./p[@class="wea"]/text()')[0]
temp = WeatherLink[i].xpath('./p[@class="tem"]/span/text()')[0] + '/' + WeatherLink[i].xpath(
'./p[@class="tem"]/i/text()')[0]
wind = WeatherLink[i].xpath('./p[@class="win"]/i/text()')[0]
WeatherList.append([date, weather, temp, wind])
# 打印天气信息
for weather in WeatherList:
print(weather)
```
相关推荐
![](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)