美文网首页爬虫
爬虫抓取静态网页和动态网页

爬虫抓取静态网页和动态网页

作者: 天星的破碎 | 来源:发表于2019-07-31 15:20 被阅读0次

抓取静态页面

静态页面中的数据都包含在网页的HTML中(一般都是get请求)

所需要的包解读
requests为常见网络请求包
lxml解析生成xml对象
xpath是一门在 XML 文档中查找信息的语言

静态网页抓取文章(网易新闻)

我们以网易新闻一个新闻页为例子,文章抓取
下面的代码是解析一篇网易文章并存储,通过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 = '<br/><img src="' + paragraph + '" alt=""><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.无头浏览器渲染
  • selenium
    selenium 为浏览器测试框架,可以调用浏览器webdriver模拟浏览器操作,Chrome_options.add_argument('--headless')设为无头模式,可以不弹出浏览器窗口
    drive.get(url),url为网页url
    下面的例子取得是网易电影: http://public.163.com/#/list/movie

selenium+chrome

#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()

相关文章

网友评论

    本文标题:爬虫抓取静态网页和动态网页

    本文链接:https://www.haomeiwen.com/subject/psjzrctx.html