这一篇我们来学习如何对多页的网络进行信息爬取。在平时网页浏览时不少看见许多网页是有多页的,像这样:
竟然,上一篇我们学会了单页网络信息的爬取,那么对于多页网络........这当然也不是问题(罒ω罒)。
首先第一步还是得学会分析,怎么分析,首先我们需要分析网页换页发生了说明改变,这里主要从URL和请求信息两个方面进行研究,我们仍以上一篇文章中的网站作为示例:
当我们不断换页时,我们会发现什么呢?没错,“看破真相的是一个外表看似小孩,智慧却过于常人的.........”:
可以发现“?”后面的“o=a{}”发生了改变,且该改变是有迹可循的每一次a后的值都会有规律的增加,那么抓住这个特征我们就可以开始构建爬虫了(*^▽^*),我们以上一篇的程序为基础,将它封装成函数,然后在进行循环调用。
def get_info(url,data = None):
wb_data = requests.get(url)#网址请求,返回response
#解析网页
#.text将网页资料变得可读
soup = BeautifulSoup(wb_data.text,'lxml')
titles = soup.select('div.listing_title > a')
images = soup.select('div.photo_booking > a > span > img')
description = soup.select('div.listing_description > span')
duration = soup.select('div.product_duration')
price = soup.select('div.product_price_info > div.price_test > div.from > span')for title,image,des,time,money in zip(titles,images,description,duration,price):
data = {
'title' : title.get_text(),
'image' : image.get('src'),
'description' : des.get_text(),
'duration' : time.get_text(),
'price' : money.get_text()
}
print(data)for i in range(30,150,30):
url = 'https://cn.tripadvisor.com/Attraction_Products-g60763-a_sort.-d1687489-The_National_9_11_Memorial_Museum-New_York_City_New_York.html?o=a{}#ATTRACTION_LIST'.format(str(i))
get_info(url)