网址:中国保护知识产权网
本次爬取的是国际新闻部分
需要爬取的是文章标题,对应的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()