程序解决问题描述如下:
利用网络爬虫在一个2022年高考倒计时网站上爬取距离2022年高考的天数,并将爬取到的高考倒计时天数以文本文件保存到电脑磁盘中。
打开网址按F12可以看到我们利用网络爬虫从网址获取的HTML,然后利用beautifulsoup库进行翻译。
程序代码如下:
# -!- coding: utf-8 -!-
import requests
from bs4 import BeautifulSoup
import os
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.select("body"):
hdfd = tr.select('.label.label-danger')
if len(hdfd) > 0:
btw = hdfd[0].text
with open('gaokaodaojishi.txt', 'a', encoding='utf-8') as f:
f.writelines('2022年高考倒计时:')
f.writelines(btw)
f.writelines('天')
def main():
url = 'https://www.haomeili.net/DaojiShi/GaoKao/'
html = getHTMLText(url)
if os.path.exists('gaokaodaojishi.txt'):
os.remove('gaokaodaojishi.txt')
fillUnivList(html)
main()
程序运行结果如下:
看到这里的小伙伴别忘了点个赞再走哦!
关注博主学习更多Python程序设计知识!