想要每天看到新聞數(shù)據(jù)又不想占用太多時(shí)間去整理,萌生自己抓取新聞網(wǎng)站的想法。
1. 準(zhǔn)備工作
使用python語(yǔ)言可以快速實(shí)現(xiàn),調(diào)用BeautifulSoup
包里面的方法
安裝BeautifulSoup
pip install BeautifulSoup
完成以后引入項(xiàng)目
2. 開發(fā)
定義請(qǐng)求頭,方便把請(qǐng)求包裝成正常的用戶請(qǐng)求,防止被拒絕
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36"
}
定義被抓取的url,并請(qǐng)求加上請(qǐng)求頭
response = requests.get(url=url, headers=headers)
BeautifulSoup解析
soup = BeautifulSoup(response.text, "html.parser")
分析網(wǎng)站需要提取數(shù)據(jù)的標(biāo)簽
因?yàn)楂@取的對(duì)象是li標(biāo)簽的第一個(gè),即
divs = soup.find(class_="js-item item")
這樣默認(rèn)就是第一個(gè),如果需要獲取全部,則需要find_all,遍歷集合
防止獲取到的新聞是當(dāng)天的做一個(gè)日期判斷
a = first_div.find(class_="title")
if a.getText().__contains__(datetime.date.today().strftime("%#m月%#d日")):
日期存在title里面所以為了判斷單獨(dú)取一下信息
然后要取到最新日期的新聞自己的url,并get請(qǐng)求這個(gè)url
b = a.get('href')
response = requests.get(url=b, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
打開新的網(wǎng)址后分析網(wǎng)站標(biāo)簽信息
取這個(gè)標(biāo)簽,獲取到p
標(biāo)簽的值
body = soup.find(class_="post_body")
p = body.find_all('p')
獲取到的是個(gè)數(shù)組,去掉第一個(gè)元素,從第二個(gè)開始即是我們需要的結(jié)果
p_id_tag = p[1].__str__()
輸出的信息帶有元素標(biāo)記,使用正則處理一下
raw_text = re.findall(r'<p[^>]*>(.*?)</p>', p_id_tag).__str__()
# 去掉 HTML 標(biāo)簽并換行顯示
clean_text = raw_text.replace('<br/>', '\n').replace('<p>', '').replace('</p>', '').replace("']",
"").replace(
"['", "").replace(r"\u200b", "")
然后把抓取的信息寫入txt
file = open("C:\\Users\\Administrator\\Desktop\\每日新聞" + '.txt',
'w', encoding='utf-8')
file.write(clean_text)
file.close()
最后使用定時(shí)任務(wù)每天定時(shí)抓取,這樣就可以每天更新了文章來源:http://www.zghlxwxcb.cn/news/detail-638028.html
schedule.every().day.at("08:00").do(getNews)
while True:
schedule.run_pending()
time.sleep(1)
運(yùn)行效果文章來源地址http://www.zghlxwxcb.cn/news/detail-638028.html
到了這里,關(guān)于python爬蟲實(shí)戰(zhàn)(1)--爬取新聞數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!