用python爬取中国保护知识产权网

网址:中国保护知识产权网
本次爬取的是国际新闻部分
需要爬取的是文章标题,对应的url、日期和内容
打开开发者模式(Ctrl+Shift+i),找到Network 下的XHR,按(Ctrl+R)进行刷新。
在这里插入图片描述
分析Headers
在这里插入图片描述
可以发现请求方式是POST,表单数据由pageNumber和cid组成
我们换第二页看看什么数据会发生变化
对比第一页
在这里插入图片描述
我们可以发现url没有发生变化,发生变化的只有pageNumber,所以可以通过修改pageNumber来实现批量爬取。
接下来看看这XHR里有什么内容,点击Preview,查看内容
在这里插入图片描述

这应该这个地方
点开其中一个看看
在这里插入图片描述
可以看到似乎乱码了,不过没关系,先不管这个,一步一步来。
现在已经知道大致思路了,应该可以爬取了

import re
import os
import requests
from bs4 import BeautifulSoup
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36 FS"}
import csv

获取json格式的数据
注意: 这是requests.post()

def get_json(data):
    url = 'http://ipr.mofcom.gov.cn/ipr/front/www/listN'
    r = requests.post(url=url, headers=headers, data=data)
    r.status_codea = r.apparent_encoding
    print("状态:", r.raise_for_status)
    return r.json()

在这里插入图片描述可以发现,居然又没乱码了。
然后我们就可以对数据进行层层剥离

def get_title_url_time(text):
    lists = []
    head_url = 'http://ipr.mofcom.gov.cn/'
    for each in text['pageInfo']['rows']:
        lists.append((each['title'], head_url+each['url'], str(each['publishTimeStr'])))
    return lists

在这里插入图片描述
那么,我们就获得了我们想要的结果。
接下来就是获取文章内容
我们就要获取text文本内容了,而且是用requests.get()请求获取的

def get_html(url):
    try:
        r = requests.get(url=url, headers=headers)
        r.encoding = r.apparent_encoding
        print("text状态:", r.raise_for_status)
        return r.text
    except Exception as result:
        print("错误原因0:", result)
        return ''

定位到文章内容,可以发现在section class=“artCon” 包含我们所爬取的内容
在这里插入图片描述

def get_we_need(text):
    soup = BeautifulSoup(text, 'lxml')
    article = soup.find('section', attrs={"class":"artCon"})
    for each in article.find_all('p'):
        print(each.string)

在这里插入图片描述
这样大致就爬取完成了
完整代码

import re
import os
import requests
from bs4 import BeautifulSoup
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36 FS"}
import csv

def get_json(data):
    url = 'http://ipr.mofcom.gov.cn/ipr/front/www/listN'
    r = requests.post(url=url, headers=headers, data=data)
    r.status_codea = r.apparent_encoding
    print("状态:", r.raise_for_status)
    return r.json()

def get_html(url):
    try:
        r = requests.get(url=url, headers=headers)
        r.encoding = r.apparent_encoding
        print("text状态:", r.raise_for_status)
        return r.text
    except Exception as result:
        print("错误原因0:", result)
        return ''

def save_title_url_time(all_list):
    path = '../file/'
    header = ['标题', 'url', '日期']
    if not os.path.exists(path):
        os.makedirs(path)
    print("开始写入")
    with open(path+'国际新闻.csv', 'w', newline="") as fp:
        f_csv = csv.writer(fp)
        f_csv.writerow(header)
        f_csv.writerows(all_list)
    print("OK")

def save_file(url, title):
    key = '国际新闻'
    if not os.path.exists(f'../file/{key}/'):
        os.makedirs(f'../file/{key}/')
    text = get_html(url)
    if not text:
        print("为空,写入失败")
    else:
        soup = BeautifulSoup(text, 'lxml')
        try:
            fp = open(f'../file/{key}/{title}.txt', 'w', encoding='utf-8')
            soup = BeautifulSoup(text, 'lxml')
            article = soup.find('section', attrs={"class":"artCon"})
            for each in article.find_all('p'):
                if each.string:
                    fp.writelines(each.string)
            fp.close()
        except Exception as result:
            print("错误原因:", result)
        print("写入成功")

def main():
    all_lists = []
    # 爬取的页数,修改数字就可以控制爬取的页数
    for i in range(1, 2):
        data = {'pageNumber': str(i),
            'cid': 'gjxw'}
        text = get_json(data)
        all_lists += get_title_url_time(text)
    # 保存到了'../file/'
    save_title_url_time(all_lists)
    for title, url, time in all_lists:
        print("开始保存:", title)
        save_file(url, title)

main()
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是强筱华哇!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值