抓取动态网页(抓取静态页面中的数据都包含在网页的HTML中 )

优采云 发布时间: 2021-09-27 20:05

  抓取动态网页(抓取静态页面中的数据都包含在网页的HTML中

)

  抓取静态页面。静态页面中的数据收录在网页的HTML中(通常是get请求)

  所需的包解释

  请求是常见的网络请求包

  Lxml解析生成XML对象

  XPath是一种用于在XML文档中查找信息的语言

  静态网页捕获文章(网易新闻)

  我们以网易新闻的一个新闻页面为例文章capture

  下面的代码解析网易文章并存储它。它是通过XPath解析从网页的静态源代码中获得的

  #coding=utf-8

import requests

from lxml import etree

import json

class WangyiCollect():

def __init__(self,url):

self.url = url

def responseHtml(self):

#获取网页源码

content = requests.get(url=self.url).text

#初始化生成一个XPath解析对象

html = etree.HTML(content)

#提取文章页内容,采用xpath解析方式

title = html.xpath('//h1/text()')[0]

pubTime = html.xpath('//div[@class="post_time_source"]/text()')[0].replace('来源:', '').strip()

pubSource = html.xpath('//a[@id="ne_article_source"]/text()')[0]

contentList = html.xpath('//div[@id="endText"]/p//text() | //div[@id="endText"]//img/@src')

newContentList = []

for paragraph in contentList:

newparagraph = paragraph

if paragraph.endswith('.jpg') or paragraph.endswith('.png') or paragraph.endswith('.gif') or paragraph.startswith('http'):newparagraph = '

' + paragraph + '<br /><br />'

newContentList.append(newparagraph)

content = ''.join(newContentList)

#存储文章内容,存储格式为json格式

articleJson = {}

articleJson['title'] = title

articleJson['pubTime'] = pubTime

articleJson['pubSource'] = pubSource

articleJson['content'] = content

print(json.dumps(articleJson,ensure_ascii=False))

#之前为字典,需要转成json的字符串

strArticleJson = json.dumps(articleJson,ensure_ascii=False)

self.writeFile(strArticleJson)

#写入文本文件

def writeFile(self,text):

file = open('./wangyiArticle.txt','a',encoding='utf-8')

file.write(text+'\n')

if __name__=="__main__":

wangyiCollect = WangyiCollect('http://bj.news.163.com/19/0731/10/ELDHE9I604388CSB.html')

wangyiCollect.responseHtml()

  抓取动态加载的网页

  结构化数据:JSON、XML等

  动态页面和静态页面之间的主要区别在于在刷新数据时使用Ajax技术。刷新数据时,将从数据库中查询数据并重新呈现到前端页面。数据存储在网络包中,无法通过爬行HTML获取数据

  获取此动态页面有两种常见方法:

  1.抓取网络请求包,请求接口传递一些参数,并破解参数。这将写在未来的博客,破解JS和破解参数

  

  image.png

  您可以看到右侧网络包中的文章数据是通过chrome数据包捕获通过数据包传输的

  取出网络包的地址请求数据,它是JSON格式的数据片段

  {

"title":"智能垃圾回收机重启 居民区里遇冷",

"digest":"",

"docurl":"[http://bj.news.163.com/19/0729/10/EL8DU15104388CSB.html](http://bj.news.163.com/19/0729/10/EL8DU15104388CSB.html)",

"commenturl":"[http://comment.tie.163.com/EL8DU15104388CSB.html](http://comment.tie.163.com/EL8DU15104388CSB.html)",

"tienum":"0",

"tlastid":"",

"tlink":"",

"label":"",

"keywords":[

{

"akey_link":"/keywords/5/0/5c0f9ec472d7/1.html",

"keyname":"小黄狗"

},

{

"akey_link":"/keywords/5/d/56de6536673a/1.html",

"keyname":"回收机"

}

],

"time":"07/29/2019 10:39:26",

"newstype":"article",

"imgurl":"[http://cms-bucket.ws.126.net/2019/07/29/3df7d178db854a33ac04c69d99dcf398.jpeg](http://cms-bucket.ws.126.net/2019/07/29/3df7d178db854a33ac04c69d99dcf398.jpeg)",

"add1":"",

"add2":"",

"add3":"",

"pics3":[

],

"channelname":"bendi"

}

  获取JSON数据

  #coding=utf-8

import requests,json

content = requests.get('https://house.163.com/special/00078GU7/beijign_xw_news_v1_02.js?callback=data_callback').text

#取出来的为json字符串

jsonArticle = content.split('data_callback(')[1].rstrip(')')

#将json字符串转为字典格式

dictArticleList = json.loads(jsonArticle)

for dictArticle in dictArticleList:

#取出title

title = dictArticle['title']

print(title)

  2.无头浏览器渲染

  硒+铬

  #coding=utf-8

from selenium import webdriver

Chrome_options = webdriver.ChromeOptions()

Chrome_options.add_argument('--headless')

drive = webdriver.Chrome(chrome_options=Chrome_options)

drive.get('http://public.163.com/#/list/movie')

html = drive.page_source

print(html)

drive.quit()

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线