写一段爬取天气的python代码,爬取对象为国内网站
时间: 2024-06-10 08:05:10 浏览: 13
好的,以下是一段简单的爬取中国天气网的天气预报信息的Python代码。
```python
import requests
from bs4 import BeautifulSoup
# 爬取中国天气网的天气预报信息
url = 'http://www.weather.com.cn/weather/101010100.shtml'
response = requests.get(url)
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
temp = soup.select('.tem span')
weather = soup.select('.wea')
wind = soup.select('.win i')
# 打印天气预报信息
print('今日天气:', weather[0].text)
print('今日温度:', temp[0].text + '/' + temp[1].text)
print('风力风向:', wind[0].text + wind[1].text)
```
请注意,在爬取网站的过程中,应该遵守网站的爬虫策略,不要过度请求网站,以免对网站造成不必要的压力。此外,无论爬取什么网站数据,请遵守相关法律法规的规定。
相关问题
写一段爬取天气的python代码
可以使用第三方库 requests 和 BeautifulSoup 来爬取天气信息。代码如下:
```
import requests
from bs4 import BeautifulSoup
def get_weather(city_name):
# 请求 URL
url = f'https://www.google.com/search?q={city_name}天气'
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.raise_for_status()
# 解析网页数据
soup = BeautifulSoup(response.text, 'lxml')
weather_info = soup.select_one('#wob_tm').text
weather = soup.select_one('#wob_dc').text
return weather_info, weather
city_name = '北京'
weather_info, weather = get_weather(city_name)
print(f'{city_name}的天气:{weather_info} {weather}')
```
这段代码实现了通过爬取 Google 搜索的天气结果来获取天气信息。
请为我用python写一段爬取视频的代码
好的,以下是使用Python爬取视频的示例代码:
```python
import requests
import os
# 定义一个函数,传入视频链接和保存目录
def download_video(video_url, save_dir):
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'}
res = requests.get(video_url, headers=headers, stream=True)
# 获取文件名
file_name = os.path.basename(video_url)
# 拼接下载路径
file_path = os.path.join(save_dir, file_name)
# 按块下载文件
with open(file_path, 'wb') as f:
for chunk in res.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
# 调用函数,传入视频链接和保存目录
download_video('https://example.com/video.mp4', 'D:/videos')
```
请注意,涉及视频版权的爬取是违法行为,本示例代码仅供学习参考,请勿用于非法用途。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)