使用Python编写爬虫程序可以帮助我们快速抓取网页上的有用信息。例如,我们可以通过爬虫程序获取当地的天气信息。下面是Python3爬虫抓取天气信息的代码:
import requests
from bs4 import BeautifulSoup
url = 'https://www.tianqi.com/'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
date = soup.find_all('p', class_='date')[0].text
weather_img = soup.find_all('div', class_='weather-icon')[0].img['src']
weather = soup.find_all('p', class_='weather')[0].text
temp = soup.find_all('p', class_='temp')[0].text.strip()
print('日期:', date)
print('天气情况:', weather)
print('温度:', temp)
首先,我们需要导入requests和BeautifulSoup这两个库。然后,我们定义了要抓取的网页链接,并使用requests库发送请求。我们还创建了一个BeautifulSoup对象,将网页源码解析为HTML文档。接下来,我们使用find_all方法从HTML文档中找到日期、天气情况、天气图标和温度这些信息所对应的HTML元素。最后,我们将这些信息打印出来。
使用Python编写爬虫程序可以帮助我们轻松地获取需要的数据。以上就是获取天气信息的一个例子。
上一篇 jquery 修改$(this)
下一篇 jquery 什么版本稳定