python爬取网络小说_Python爬取起点中文网月票榜前500名网络小说介绍
觀察網頁結構
進入起點原創風云榜:http://r.qidian.com/yuepiao?chn=-1
老套路,懂我的人都知道我要看看有多少內容和頁數需要爬。
https://ask.hellobi.com/uploads/article/20170408/0b0192094e6d073f9a16bc3211e7e904.png
編寫爬蟲
import requests
from bs4 import BeautifulSoup
res=requests.get('http://r.qidian.com/yuepiao?chn=-1&page=1')
#print(res)#中間打印看看,好習慣
soup=BeautifulSoup(res.text,'html.parser')#
篩選器
#print(soup)
for news in soup.select('.rank-view-list li'):#定位
print(news)
結果如下:
注意這些標簽(因為美麗湯提取是基于標簽的)
經過測試
for news in soup.select('.rank-view-list li'):#Wrap后面一定有個空格,因為網頁里有
#print(news)
print(news.select('a')[1].text,news.select('a')[2].text,news.select('a')[3].text,news.select('p')[1].text,news.select('p')[2].text,news.select('a')[0]['href'])
可以設置提取內容如上面代碼所示
提取結果是:
很亂,把內容存成字典格式再存放到列表中:
for news in soup.select('.rank-view-list li'):#Wrap后面一定有個空格,因為網頁里有
#print(news)
#print(news.select('a')[1].text,news.select('a')[2].text,news.select('a')[3].text,news.select('p')[1].text,news.select('p')[2].text,news.select('a')[0]['href'])
newsary.append({'title':news.select('a')[1].text,'name':news.select('a')[2].text,'style':news.select('a')[3].text,'describe':news.select('p')[2].text,'url':news.select('a')[0]['href']})
使用pandas的DataFrame格式存放
使用循環爬取25頁內容
import requests
from bs4 import BeautifulSoup
newsary=[]
for i in range(25):
res=requests.get('http://r.qidian.com/yuepiao?chn=-1&page='+str(i))
#print(res)
soup=BeautifulSoup(res.text,'html.parser')
#print(soup)
#for news in soup.select('.rank-view-list h4'):#Wrap后面一定有個空格,因為網頁里有
for news in soup.select('.rank-view-list li'):#Wrap后面一定有個空格,因為網頁里有
#print(news)
#print(news.select('a')[1].text,news.select('a')[2].text,news.select('a')[3].text,news.select('p')[1].text,news.select('p')[2].text,news.select('a')[0]['href'])
newsary.append({'title':news.select('a')[1].text,'name':news.select('a')[2].text,'style':news.select('a')[3].text,'describe':news.select('p')[1].text,'lastest':news.select('p')[2].text,'url':news.select('a')[0]['href']})
import pandas
newsdf=pandas.DataFrame(newsary)
newsdf
總結
以上是生活随笔為你收集整理的python爬取网络小说_Python爬取起点中文网月票榜前500名网络小说介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 学习笔记(14):零基础掌握 Pytho
- 下一篇: 第四章 网络互联