爬取美团新闻信息,此处采用两种方法实现:
注意点:因为此处的数据都是动态数据,所以一定要考虑好向下滑动数据包会更新的情况,不然就只能读取当前页即第一页数据,方法一通过更新ajax数据包网址页数,方法二通过计算网页高度滚动到底部实现持续向下滑动过程。
方法一:
使用寻找包含数据的ajax请求(json数据)的数据包,通过jsonpath定位提取出想要的数据:
# -- coding: utf-8 --
# 爬取内容:标题,标签,简介
import requests
import json
import jsonpath
import pprintnum = 1
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36','cookie': '_lxsdk_cuid=192b4109d3bc8-0ab8530f770fd3-26001051-144000-192b4109d3bc8; logan_session_token=s9yzimqoliqqqa0xxruc; cookie_consent=true; _lxsdk_s=192b4109d3c-294-7f6-c00%7C%7C12'
}
while num <= 10:url = f'https://www.meituan.com/smart/view/news/r/tNewsService_pageGetByQuery?pageSize=10&pageNo={num}&newsClassifyId=&lanType=zh-CN'response = requests.get(url, headers=headers)dict_data = json.loads(response.content)# pprint.pprint(dict_data)titles = jsonpath.jsonpath(dict_data, '$..title')signs = jsonpath.jsonpath(dict_data, '$..newsClassifyName')contents = jsonpath.jsonpath(dict_data, '$..newsAbstract')comment_list = []for title, sign, comment in zip(titles, signs, contents):comment_dict = {"标题": title,"标签": sign,"简介": comment,}comment_list.append(comment_dict)print(json.dumps(comment_list, ensure_ascii=False, indent=4))num += 1
爬取结果:
方法二:
使用selenium进行自动化操作,通过xpath定位数据实现对数据的提取:
# -- coding: utf-8 --
from selenium import webdriver
from selenium.webdriver.common.by import By
import timedriver = webdriver.Chrome()
driver.get('https://www.meituan.com/news?requestCode=b872f8728bc74f9f9c90688d88b58e1d&responseCode=ff49426a9e664f6ba92cbaa7fc9b9b08')# 等待页面加载
time.sleep(3)
# 设置滚动和爬取参数
scroll_pause_time = 2 # 每次滚动后的等待时间
previous_height = driver.execute_script("return document.body.scrollHeight") #JavaScript 代码返回当前网页的总高度# 循环进行滚动和数据爬取
while True:# 获取当前页面的元素列表el_list = driver.find_elements(By.XPATH, '//*[@id="__next"]/div[2]/div[2]/div/div[2]/a/div/div[1]/div')# 输出当前爬取的内容for el in el_list:title = el.find_element(By.XPATH, './/h2').textsign = el.find_element(By.XPATH, './/div[2]/span[1]/span').textcontent = el.find_element(By.XPATH, './/div[1]').textcomment_dict = {"标题": title,"标签": sign,"简介": content,}print(comment_dict) # 输出当前获取的数据# 滚动到页面底部driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")# 等待新内容加载time.sleep(scroll_pause_time)# 计算新的滚动高度new_height = driver.execute_script("return document.body.scrollHeight")if new_height == previous_height:break # 如果没有更多内容,退出循环previous_height = new_heightdriver.quit()
爬取结果: