python爬蟲爬取指定內(nèi)容的解決方法
爬取一些網(wǎng)站下指定的內(nèi)容,一般來說可以用xpath來直接從網(wǎng)頁上來獲取,但是當(dāng)我們獲取的內(nèi)容不唯一的時(shí)候我們無法選擇,我們所需要的、所指定的內(nèi)容。
解決辦法:
可以使用for In 語句來判斷
如果我們所指定的內(nèi)容在這段語句中我們就把這段內(nèi)容爬取下來,反之就丟棄
實(shí)列代碼如下:(以我們學(xué)校為例)
import urllib.request from lxml import etree def creat_url(page): if(page==1): url='https://www.qjnu.edu.cn/channels/9260.html' else: url='https://www.qjnu.edu.cn/channels/9260_'+str(page)+'.html' headers={ 'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53' } request = urllib.request.Request(url=url,headers=headers) return request def creat_respons(request): respons = urllib.request.urlopen(request) content = respons.read().decode('utf-8') return content def down_2(url): url = url headers = { 'User-Agent': ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36 Edg/100.0.1185.29' } request = urllib.request.Request(url=url, headers=headers) response = urllib.request.urlopen(request) content2 = response.read().decode('utf-8') tree2 = etree.HTML(content2) return tree2 def down_loads(content): tree = etree.HTML(content) name_list = tree.xpath('//div[@class="media"]/h4/a/text()') url_list = tree.xpath('//div[@class="media"]/h4/a/@href') for i in range(len(name_list)): if key in name_list[i]: with open('學(xué)校黨員主題網(wǎng)址.txt', 'a', encoding='UTF-8') as fp: fp.write(url_list[i]+'\n') url = url_list[i] tree = down_2(url) tex_list = tree.xpath('//div[@class="field-item even"]//p/span/text()') name = name_list[i] with open(name + '.txt', 'w', encoding='UTF-8') as fp: fp.write(str(tex_list)) if __name__ == '__main__': all_page=int(input('請輸入要爬取頁碼:')) key = str(input('請輸入關(guān)鍵詞:')) s_page=1 for page in range(s_page,all_page+1): request=creat_url(page) content=creat_respons(request) down_loads(content)
此段代碼的可執(zhí)行性沒有問題,邏輯上也能夠串通
但是代碼冗余較多,看起來有點(diǎn)復(fù)雜,現(xiàn)在正在研究簡化版的代碼!
到此這篇關(guān)于python爬蟲爬取指定內(nèi)容的解決方法的文章就介紹到這了,更多相關(guān)python爬取指定內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python爬蟲爬取bilibili網(wǎng)頁基本內(nèi)容
- Python爬蟲爬取百度搜索內(nèi)容代碼實(shí)例
- python爬蟲開發(fā)之使用python爬蟲庫requests,urllib與今日頭條搜索功能爬取搜索內(nèi)容實(shí)例
- python爬取內(nèi)容存入Excel實(shí)例
- Python爬蟲爬取新浪微博內(nèi)容示例【基于代理IP】
- python爬取網(wǎng)頁內(nèi)容轉(zhuǎn)換為PDF文件
- Python下使用Scrapy爬取網(wǎng)頁內(nèi)容的實(shí)例
- 基于Python實(shí)現(xiàn)web網(wǎng)頁內(nèi)容爬取的方法
相關(guān)文章
pytorch訓(xùn)練時(shí)的顯存占用遞增的問題解決
本文主要介紹了pytorch訓(xùn)練時(shí)的顯存占用遞增的問題解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01python 偷懶技巧——使用 keyboard 錄制鍵盤事件
這篇文章主要介紹了python如何使用 keyboard 錄制鍵盤事件,幫助大家提高工作效率,感興趣的朋友可以了解下2020-09-0950行Python代碼獲取高考志愿信息的實(shí)現(xiàn)方法
這篇文章主要介紹了50行Python代碼獲取高考志愿信息的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07