python抽取指定url页面的title_Python使用scrapy爬虫,爬取今日头条首页推荐新闻

本文介绍如何使用Python的Scrapy框架结合Selenium和PhantomJS,抓取今日头条首页通过js动态生成的推荐新闻。通过分析接口地址https://www.toutiao.com/api/pc/focus/获取JSON数据,最终实现对新闻标题和内容的爬取。
摘要由CSDN通过智能技术生成

爬取今日头条https://www.toutiao.com/首页推荐的新闻,打开网址得到如下界面

cba29c8bf4b59f383f55f2bec3f6a0f2.png

查看源代码你会发现

07c55c8fde0ff6a4309c6a11c715672a.png

全是js代码,说明今日头条的内容是通过js动态生成的。

用火狐浏览器F12查看得知

2a99e95421acaeeedb8e270dc1b71909.png

得到了今日头条的推荐新闻的接口地址:https://www.toutiao.com/api/pc/focus/

单独访问这个地址得到

7e0a710c173501fb9eda52c0f0806743.png

此接口得到的数据格式为json数据

我们用scrapy+selenium+PhantomJS的方式获取今日头条推荐的内容

下面是是scrapy中最核心的代码,位于spiders中的toutiao_example.py

import scrapy
import json
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import re
 '''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
class ToutiaoExampleSpider(scrapy.Spider):
    name = 'toutiao_example'
    allowed_domains = ['toutiao.com']
    start_urls = ['https://www.toutiao.com/api/pc/focus/'] ###今日头条焦点的api接口
    def parse(self, response):
        conten_json=json.loads(response.text) <br>        conten_news=conten_json['data'] ###从json数据中抽取data字段数据,其中data字段数据里面包含了pc_feed_focus这个字段,其中这个字段包含了:新闻的标题title,链接url等信息
        for aa in  conten_news['pc_feed_focus']:
            title=aa['title']
            link_url='https://www.toutiao.com'+aa['display_url'] ###如果写(www.toutiao.com'+aa['display_url'])会报错,加上https://,(https://www.toutiao.com'+aa['display_url'])则不会报错!
            link_url_new=link_url.replace('group/','a')###把链接https://www.toutiao.com/group/6574248586484122126/,放到浏览器中,地址会自动变成https://www.toutiao.com/a6574248586484122126/这个。所以我们需要把group/ 替换成a
 
            yield scrapy.Request(link_url_new, callback=self.next_parse)
 
    def next_parse(self, response):
 
        dcap = dict(DesiredCapabilities.PHANTOMJS)  # 设置useragent信息
        dcap['phantomjs.page.settings.userAgent'] = (
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0 ')  # 根据需要设置具体的浏览器信息
        driver = webdriver.PhantomJS(desired_capabilities=dcap)  #封装浏览器信息) # 指定使用的浏览器,
 
        #driver.set_page_load_timeout(5)  # 设置超时时间
        driver.get(response.url)##使用浏览器请求页面
 
        time.sleep(3)#加载3秒,等待所有数据加载完毕
   
        
        title=driver.find_element_by_class_name('title').text  ###.text获取元素的文本数据
        content1=driver.find_element_by_class_name('abstract-index').text###.text获取元素的文本数据
        content2=driver.find_element_by_class_name('abstract').text###.text获取元素的文本数据
 
        content=content1+content2
 
        print(title,content,6666666666666666)
        driver.close()
  
      #data = driver.page_source# 获取网页文本
      #driver.save_screenshot('1.jpg')  # 系统截图保存

运行代码我们得到结果为标题加内容呈现方式如下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值