[使用案例]如何使用ip代理獲取UC新聞內容
選擇優(yōu)質的ip代理,我們能夠利用它來完成很多網絡工作,比如網上的大數據抓取,其實就是要依靠ip代理來進行的。今天,IP海向大家介紹一個爬取新聞網站內容的教程。
IP海以UC網站為例子:
這個網站并沒有太復雜的反爬蟲,我們可以直接解析爬取就好。
from bs4 import BeautifulSoup
from urllib import request
def download(title,url):
req = request.Request(url)
response = request.urlopen(req)
response = response.read().decode('utf-8')
soup = BeautifulSoup(response,'lxml')
tag = soup.find('div',class_='sm-article-content')
if tag == None:
return 0
title = title.replace(':','')
title = title.replace('"','')
title = title.replace('|','')
title = title.replace('/','')
title = title.replace('\','')
title = title.replace('*','')
title = title.replace('<','')
title = title.replace('>','')
title = title.replace('?','')
with open(r'D:codepythonspider_newsUC_newssociety\' + title + '.txt','w',encoding='utf-8') as file_object:
file_object.write(' ')
file_object.write(title)
file_object.write(' ')
file_object.write('該新聞地址:')
file_object.write(url)
file_object.write(' ')
file_object.write(tag.get_text())
#print('正在爬取')
if __name__ == '__main__':
for i in range(0,7):
url = 'https://news.uc.cn/c_shehui/'
# headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36",
# "cookie":"sn=3957284397500558579; _uc_pramas=%7B%22fr%22%3A%22pc%22%7D"}
# res = request.Request(url,headers = headers)
res = request.urlopen(url)
req = res.read().decode('utf-8')
soup = BeautifulSoup(req,'lxml')
#print(soup.prettify())
tag = soup.find_all('div',class_ = 'txt-area-title')
#print(tag.name)
for x in tag:
news_url = 'https://news.uc.cn' + x.a.get('href')
print(x.a.string,news_url)
download(x.a.string,news_url)
這樣,我們就完成了網站新聞數據的抓取,可以檢查運行結果看到,我們的數據是否成功獲得。
版權聲明:本文為IP海(iphai.cn)原創(chuàng)作品,未經許可,禁止轉載!
Copyright © www.wibm.ac.cn. All Rights Reserved. IP海 版權所有.
IP海僅提供中國內IP加速服務,無法跨境聯(lián)網,用戶應遵守《服務條款》內容,嚴禁用戶使用IP海從事任何違法犯罪行為。
鄂ICP備19030659號-3
鄂公網安備42100302000141號
計算機軟件著作權證
ICP/EDI許可證:鄂B2-20200106