爬虫实战操作(3)—— 获取列表下的新闻、诗词
生活随笔
收集整理的這篇文章主要介紹了
爬虫实战操作(3)—— 获取列表下的新闻、诗词
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文前兩部分想實現:給定鏈接,獲取分頁的新聞標題內容,部分程序參考爬蟲實戰操作(2)一新浪新聞內容細節,爬蟲的鏈接是國際新浪網。
1. 單個新聞
獲取國際新聞最新消息下得單個信息內容
根據上面得鏈接簡單修改了下程序參數,主要是評論數得修改。
2. 列表新聞
思想:
先找到控制網頁分頁的url,如下面的圖示
再獲取每一頁的所有新聞的鏈接
接著獲取每個鏈接的內容
最后修改分頁url的頁碼
3. 列表詩詞
詩詞鏈接:https://www.shicimingju.com/chaxun/zuozhe/9_2.html
1.先獲取每一頁的詩詞的鏈接
url='http://www.shicimingju.com/chaxun/zuozhe/9.html' base='https://www.shicimingju.com' headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \(KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'} #使用headers(客戶端的一些信息),偽裝為人類用戶,使得服務器不會簡單地識別出是爬蟲 r=requests.get(url,headers=headers) html=r.text.encode(r.encoding).decode() soup=BeautifulSoup(html,'lxml') div=soup.find('div',attrs={'class':'card shici_card'}) hrefs=[h3.find('a')['href'] for h3 in div.findAll('h3')] hrefs=[base+i for i in hrefs] hrefs2.再獲取所有頁碼下的所有詩詞的鏈接
def gethrefs(url):headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \(KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}#使用headers(客戶端的一些信息),偽裝為人類用戶,使得服務器不會簡單地識別出是爬蟲base='https://www.shicimingju.com'nexturl=urlans=[]while nexturl!=0:r=requests.get(nexturl,headers=headers)html=r.text.encode(r.encoding).decode()soup=BeautifulSoup(html,'lxml')div=soup.find('div',attrs={'class':'card shici_card'})hrefs=[h3.find('a')['href'] for h3 in div.findAll('h3')]hrefs=[base+i for i in hrefs]try:nexturl=base+soup.find('a',text='下一頁')['href']print('讀取頁碼中')except Exception as e:print('已經是最后一頁')nexturl=0ans.append(hrefs)return ans3.獲取每個連接下的古詩內容
def writeotxt(url):headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \(KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}#使用headers(客戶端的一些信息),偽裝為人類用戶,使得服務器不會簡單地識別出是爬蟲r=requests.get(url,headers=headers)soup=BeautifulSoup(r.text.encode(r.encoding),'lxml')#數據清洗titile=soup.find('h1',id='zs_title').textcontent=soup.find('div',class_='item_content').text.strip()#先建一個文件夾firedir=os.getcwd()+'蘇軾的詞'if not os.path.exists(firedir):os.mkdir(firedir)with open (firedir+'/%s.txt'%title,mode='w+',encoding='utf-8') as f:f.write(title+'\n')f.write(content+'\n')print('正在載入第 %d首古詩。。。'%i)總結
以上是生活随笔為你收集整理的爬虫实战操作(3)—— 获取列表下的新闻、诗词的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电脑店能安装mysql_用U盘给台式机安
- 下一篇: 使用U盘PE修复电脑常规问题