一、写入值到word
二、spider爬取标题进行写入
三、爬去代码并将代码进行装换
遇到问题:
代码块中,每一个字符都是有span进行包装
http://tools.jb51.net/code/jb51_c_format
这个方法可以直接把代码的值获取到,可以通过它来进行获取代码
思路一、直接模仿代码进行在线装换,并进行写入操作
思路二、使用文件操作技术获取装换后的代码,后使用脚本复制粘贴进word文档
思路三、通过对span标签的直接获取值进行拼接,把拼接后的值传入word(选择)
最后使用etree对代码块进行解析
工程遇到的工具:
https://www.jb51.net/article/161053.htm(etree)
https://blog.csdn.net/sinat_38682860/article/details/100165446(equery)
代码:
import requests
from bs4 import BeautifulSoup
from pyquery import PyQuery as pq
from lxml import etree
from docx import Document
from docx.shared import Inches
url="https://www.runoob.com/cprogramming/c-exercise-example"
def geu_page(url):
try:
res = requests.get(url,timeout=4)
res.encoding = 'utf-8'
if res.status_code == 200:
html = res.text
return html.encode("utf-8")
except Exception as e:
for i in range(3):
print(url,e)
res = requests.get(url,timeout=4)
res.encoding = 'utf-8'
if res.status_code == 200:
html = res.text
return html.encode('utf-8')
def getdata(url1):
html1 = geu_page(url1)
doc = pq(html1) # 解析html文件
datas = etree.HTML(html1)
data = datas.xpath('//div[@class="hl-main"]/span/text()')
code = ''.join(data)
title = doc('#content > p:nth-child(3)').text() # 其中doc(使用的是selector选择器)
content = doc('#content > p:nth-child(4)').text()
# 对url进行切割获取下标
begin = url1.find("example")
end = url1.find(".html")
index = url1[begin + 7:end]
print("开始写入第"+index+"个实例")
write_to_word(code,title,content,head=index)
def write_to_word(code,title,content,head):
# 标题
document.add_heading("C语言实例"+str(head), level=0)
# 文本: 题目
document.add_paragraph(title)
# 文本: 程序分析
document.add_paragraph(content)
# 代码: 代码
document.add_paragraph(code)
# 结果: result
document = Document()
for i in range(1,101):
url1=url+str(i)+".html"
getdata(url1)
document.save('C 语言经典100例.docx')
ent()
for i in range(1,101):
url1=url+str(i)+".html"
getdata(url1)
document.save('C 语言经典100例.docx')