在Python中,我们可能需要将抓取的数据在Word文档中存储和展示,可以使用一些第三方库如python-docx。这个库允许你创建、修改和提取Word文档的元素。请注意,python-docx只能处理.docx格式的文档。下面是如何使用这个库的详细步骤:
安装库:首先,通过命令pip install python-docx安装库。
创建文档:使用Document()类来创建一个新的Word文档或者打开一个现有的文档。
添加段落:通过add_paragraph()方法,你可以在文档中添加新的段落,段落会自动换行。
添加文本块:使用add_run()方法,在段落中添加文本块(Run对象),文本块不自动换行。
添加文本:通过add_text()方法,在文本块中添加文本,文本不支持插入换行符。
添加分隔符:使用add_break()方法,在文本块中添加分隔符,实现段落内的换行。
添加分页符:使用Document()类的add_page_break()方法,在文档中添加分页符。
保存文档:使用Document()类的save()方法保存你的文档。
以下是一段示例代码,展示了如何使用这些方法将数据存入Word文档:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import ssl
import pandas as pd
from urllib.parse import urljoin
import re
from docx import Document
from datetime import datetime
def create_unverified_context():
"""创建不验证服务器证书的HTTPS上下文"""
return ssl._create_unverified_context()
def get_soup(url, headers, context):
"""获取网页内容并返回BeautifulSoup对象"""
try:
# 确保URL以http开头
url = url.replace('https://', 'http://') if url.startswith('https://') else url
with requests.get(url, headers=headers, timeout=10, verify=False) as response:
response.raise_for_status()
return BeautifulSoup(response.content, "html.parser")
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e.response.status_code} - {e}")
except requests.exceptions.ConnectionError:
print("Error connecting to the server.")
except requests.exceptions.Timeout:
print("Request timed out.")
except requests.exceptions.RequestException as e:
print(f"Request error: {e}")
return None
def parse_article_soup(article_soup):
"""从BeautifulSoup对象中解析单页文章的详情"""
article_data = {
'正文': [],
'申请人': [],
'仲裁员': [],
'书记员': [],
'案由': None,
'日期': article_soup.find('meta',attrs={'name':'PubDate'}).get('content'),
'标题': article_soup.find('meta',attrs={'name':'ArticleTitle'}).get('content'),
'链接': article_soup.find('meta',attrs={'name':'Url'}).get('content'),
}
# 获取正文区域内属性style="text-align: center;"的
标签之后的所有元素
article_text_tags = article_soup.select('.news_cont_d_wrap p[style="text-align: center;"]:nth-child(2)~*')
# 获取所有标签的文本数据
i, n = 0, 0
for p in article_text_tags:
# 检查段落文本中是否包含特定关键词,并据此更新文章数据
text = re.sub(r'\s+', '', p.get_text(strip=True))
style_value = p.get('style')
# 获取案由
if text.startswith('案由'): #'案由' in re.sub(r'\s+','',p.get_text(strip=True))
article_data['案由'] = text
article_data['正文'].append(article_data['案由'])
n = i
# 获取仲裁员信息
elif text.startswith('仲裁员'):
article_data['仲裁员'].append(text)
elif text.startswith('书记员'):
article_data['书记员'].append(text)
# 处理表格
elif p.name == 'table':
rows = p.find_all('tr')
for row in rows:
columns = row.find_all('td')
# 提取单元格数据
row_data = [column.get_text(strip=True) for column in columns]
article_data['正文'].append(row_data)
# 获取案由之前的文本作为“申请人”,并过滤以“案号”开头的文本标签
elif n == 0 and text and not text.startswith('案号'):
article_data['申请人'].append(text)
# 获取案由之后的数据作为“正文”,并过滤